
  // 画布上页面的位置和大小
  const pageX = 20; // 画布左边界偏移20像素
  const pageY = 20; // 画布上边界偏移20像素
  const pageWidth = 794; // 页面宽度
  const pageHeight = 1123; // 页面高度
  var   lastTableTotalWidth=0;  //最新的表格宽度更新
  var   selectStartX=0;  //选中表格的起始X坐标
  var   selectStartY=0;  //选中表格的起始Y坐标
  var   isSelecting = false;
  var   selectionStart = {};
  var   selectedCells = [];
  var   currentSelection = [];//记录当前选择单元各的 数组下标集
  var   jsonData = [];
  var   lastTextData=null;      //临时画板上最后停留的内容：如果有选中单元格，为此赋值，当渲染之后，用这个数据渲染。
  var   lastSizeOfCellCanvas=  {   left: "0px",   top: "0px",   width:10,    height:10  };
  var   tableTotalWidth=0;
  var   tableTotalHeight=0;
  var   tableOffsetX=60;  //表格与画布的左边距
  var   tableOffsetY=60; //表格与画布的顶边距
  var   canvasOffset=null; //主画布与页面的偏移
  var   cellStartX = 0;    //canvasOffset.left+tableOffsetX;
  var   cellStartY =0;     //canvasOffset.top+tableOffsetY;
  var   startX=0;
  var   startY=0;
  var   whereCurIs=0;     //在表格边上悬浮 1,光标在单元格的上边线上, 2光标在左侧边; 3光标在第一行的上边; 4，在最下边单元格；5光标在单元格内部
  var   cursorIsInSideOfCell=0;//光标在单元格内部，，offset之内
  var   g_selectedColumn=-1;  //全局选中的列
  var   g_selectedRow=-1;     //全局选中的行
  var   g_selectedCellWidth_L=0;  //全局选单元格宽度
  
  var   g_selectedCellWidth_R=0;
  var   g_selectedCellHeight=0;  //全局选单元格高度
  var   temp_left_cell_width;
  var   temp_right_cell_width;
  var   isIntoMenuSelection=0;//弹起菜单，，其它绘图操作禁用
  var   latestSelectCells={x:-1,y:-1}; //最后一次的点击单元格 行，，列

  let   isSelectingForCell = false;                                     //是否正在选择单元格
  let   selectionStartX, selectionStartY, selectionEndX, selectionEndY; //选择区域的起始和结束坐标

    var gridSize = 15;
    var gridSpacing = 5;
    var rowSpacing = 5;
    var rows = 24, columns = 14;
    var gridColor = '#000';
    var highlightColor = 'rgba(173, 216, 230, 0.5)'; // Light blue color

    // 确保 history 和 redoStack 是数组
    var historyStack = [];
    var redoStack = [];
    var checkedBoxImage = new Image();
    var checkBoxImage = new Image();

    var originalY = 0;
    var maxWidth = 360;
    var lineHeight = 25;
    var align = 0;
    var displayMode = 1;
    var g_verticalAlign = 0;
    var font = 'Arial';
    var fontSize = 16;
    var indent = 0; // 首行缩进的字符数量
    // 全局变量来跟踪斜体状态
    var italic = 0; // 0表示正常，1表示斜体
    var underlineColor='rgb(255, 255, 0)';
    var underline=0;
    var underlineStyle = 'straight';
    var backgroundColor='transparent'
    var currentLineSpacing = 0; // 初始行距
    var bold = 0; // 初始时不加粗
    var strikethrough = 0; // 0表示没有删除线，1表示有删除线
    var allowEditCell=false;//当发现有双击单元格时，才能够对单元格进行编辑
    var lastPageNo=0;
    var lastPageName=0;
    var editor_locked_cellRecord={rows:-1,columns:-1};//用于锁定当前编程序的记录
    var boldButtonStatus=false;
    var italicButtonStatus=false;
    var underlineButtonStatus=false;
    var strikethroughButtonStatus=false;
    var underlineStyleButtonStatus=false;
    var underlineColorButtonStatus=false;
    var backgroundColorButtonStatus=false;
    var loadAtFirstTime=true;
    var isInScrolling=false;
    var currentPage = 1;
    var finishDrawTable= false;//当前表格的绘制过程完成
    var whereCallDrawTable="";//在哪调用了drawTable
  
    //最顶层文件结构
    var templateDoc = [
      //{ para: { type: "Text", content: "智能表格", url: "", rect: { left: 0, top: 0, right: 0, bottom: 0 } } },
      //{ para: { type: "Text", content: "欢迎使用\n您的支持是我最大的动力！\n", url: "", rect: { left: 0, top: 0, right: 0, bottom: 0 } } }
   
    ];
  
    let loadedImages = [];  // Array to hold loaded image objects

    // 事件总线对象
    var EventBus = {
      events: {},
      on: function(eventName, callback) {
          this.events[eventName] = this.events[eventName] || [];
          this.events[eventName].push(callback);
      },
      trigger: function(eventName, data) {
          if (this.events[eventName]) {
              this.events[eventName].forEach(function(callback) {
                  callback(data);
              });
          }
      }
    };

    function getParaIndexAt(x, y) {
      const textCanvas = document.getElementById('textCanvas');
      let canvasOffsetLeft=textCanvas.offsetLeft;
      let canvasOffsetTop=textCanvas.offsetTop;

     
      console.log("x:",x,"y:",y, " length:",templateDoc.length);
      //  x=x-canvasOffsetLeft;
      //  y=y-canvasOffsetTop;
      let currentX=x-canvasOffsetLeft;
      let currentY=y+10;
      currentY+=(currentPage-1)*985;
      console.log("offsetLeft:",canvasOffsetLeft,"offsetTop:", canvasOffsetTop," page:",currentPage," currentY:",currentY);
      for (let i = 0; i < templateDoc.length; i++) {
          let rect = templateDoc[i].para.rect;
          console.log("11=>rect.left:",rect.left,"rect.top:",rect.top,"rect.right:",rect.right,"rect.bottom:",rect.bottom," content:",templateDoc[i].para.content);
          console.log("22=>x:",currentX,"y:",currentY);
          if (currentX >= rect.left && currentX <= rect.right && currentY >= rect.top && currentY <= rect.bottom) {
              return i;
          }
      }
      return -1;
  }
  
    //文本段落定位
    function onCanvasClick(e) {
      const textcanvas = document.getElementById('textCanvas');
      const rect = textcanvas.getBoundingClientRect();
      const x = e.clientX - rect.left + window.scrollX;
      const y = e.clientY - rect.top + window.scrollY;
      const index = getParaIndexAt(x, y);
      console.log("Cursor Position - X:", x, "Y:", y); // 打印光标位置

      if (index !== -1) {  // 确保找到有效的段落
          const para = templateDoc[index].para;
          console.log("Clicked para index:", index);
          console.log("Type:", para.type);
          console.log("Content:", para.content);
          if (para.type === "Image") {
              console.log("Image URL:", para.url);
          }
      } else {
          console.log("No para was clicked.");
      }
    }

   
  

    //初始化文档页面视图
    function initPages()
    {
     

  
      // 获取canvas元素
      var g_canvas = document.getElementById("cellsCanvas");
      var g_menuAreas=document.getElementById("navBar_sbu_001");
      var temp_myTableCanvas=s=document.getElementById("myCanvas");
     
      //在光标移动或光标左键点击过程中，主动的检测当前文档被点击
      document.addEventListener("click", function(e) {

        const text_canvas = document.getElementById('textCanvas');//文本模板层 这是最终文本输出的地方
        const rect = text_canvas.getBoundingClientRect();
        const x = e.clientX - rect.left + window.scrollX;
        const y = e.clientY - rect.top + window.scrollY;
        const index = getParaIndexAt(x, y);
        console.log("Cursor Position  X:", x, "Y:", y); // 打印光标位置
    
        if (index !== -1) {  // 确保找到有效的段落
            const para = templateDoc[index].para;
            console.log("1557 Clicked para index:", index,"Type:", para.type,"Content:", para.content);
           
            if (para.type === "Image") {
                console.log("Image URL:", para.url);
            }
        } else {
            console.log("1557 No para was clicked.");
        }

      });

      var g_ctx = g_canvas.getContext("2d");

      // 监听document的鼠标移动事件
      document.addEventListener("mousemove", function(event) {
        // 获取canvas在页面上的位置
        var rect = g_canvas.getBoundingClientRect();
       

        // 计算鼠标在canvas上的相对坐标
        var x = event.clientX - rect.left;
        var y = event.clientY - rect.top;

    

        // 判断鼠标是否在canvas内部
        if (x >= 0 && x <= g_canvas.width && y >= 0 && y <= g_canvas.height||
          x >= 0 && x <= g_menuAreas.width && y >= 0 && y <= g_menuAreas.height
        ) {
          //console.log("X: " + x + ", Y: " + y);
          //  cells_selectionStart=editer_locked_selectChars.start;
          //  cells_selectionEnd=editer_locked_selectChars.end;
        } else {


          //这里要判断，当前单元格有文字选中的是哪个单元格？离开单元格时有没有点击
          document.getElementById('main_canvas').style.pointerEvents='auto';
          document.getElementById(lastPageName).style.pointerEvents='auto';
					document.getElementById('page-1').style.pointerEvents='auto';
          document.getElementById('myCanvas').style.pointerEvents = 'auto';
          document.getElementById('page-1-content_div').style.pointerEvents='none';
          // 如果你之后需要让下层canvas重新接收事件
          document.getElementById('cellsCanvas').style.pointerEvents = 'auto';
          if(editor_locked_cellRecord.rows>=0&&editor_locked_cellRecord.columns>=0)
          {
            //console.log("QQ8 old:",jsonData[editor_locked_cellRecord.rows].cells[editor_locked_cellRecord.columns]," new:",textData);
            jsonData[editor_locked_cellRecord.rows].cells[editor_locked_cellRecord.columns]=textData;   
            jsonData[editor_locked_cellRecord.rows].cells[editor_locked_cellRecord.columns].content=textData.text;  
            textData.cursorVisible=false;
            

          }
         

        }
      });


   
   
      const canvas = document.getElementById('main_canvas');
            const pageInfo = document.getElementById('page-info');
           

            for (let i = 1; i <= 10; i++) {
                const pageId = `page-${i}`;
                const page = document.createElement('div');
                page.classList.add('page');
                page.id = pageId;
                

               //动态生成页眉DIV
               const header = document.createElement('div');
               header.classList.add('header');
               //header.textContent = `页眉 - 第${i}页`;
               header.id = `${pageId}-header_div`;

               // 必须在header被实际添加到DOM后获取其宽度
               document.body.appendChild(header); 
               const W1 = header.offsetWidth; 

               //动态生成页眉画布
               const header_canvasElement = document.createElement('canvas');
               header_canvasElement.id = `${pageId}-hederCanvas`;
               header_canvasElement.width = W1; // Set the width of the canvas to the header width
              
               header_canvasElement.height = 68; // Set the height of the canvas
               header.appendChild(header_canvasElement);

               const ctxHeder = header_canvasElement.getContext('2d');
              // 设置文本样式
              ctxHeder.fillStyle = 'black';
              ctxHeder.font = '20px Arial';
              ctxHeder.textAlign = 'center';
              ctxHeder.textBaseline = 'middle';

              


              

            
               ctxHeder.lineWidth = 1;

               // Draw the original set of lines
               ctxHeder.beginPath();
               ctxHeder.moveTo(60, 68);
               ctxHeder.lineTo(70, 68);              
               ctxHeder.lineTo(70, 58);
               ctxHeder.stroke();

               // Draw the new set of lines based on the width of the header
               ctxHeder.beginPath();
               ctxHeder.moveTo(W1 - 20, 68);
               ctxHeder.lineTo(W1 - 30, 68);                          
               ctxHeder.lineTo(W1 - 30, 58);
               ctxHeder.stroke();
                // 绘制文本
               ctxHeder.fillText( `页眉 - 第${i}页`, header_canvasElement.width / 2, header_canvasElement.height / 2);

                const content = document.createElement('div');
                content.id=`${pageId}-content_div`;
                content.classList.add('content');

                const contentCanvas = document.createElement('canvas');
                contentCanvas.height = 985; // Set the height of the canvas
                contentCanvas.width = W1;
                contentCanvas.classList.add('contentCanvas');
                contentCanvas.id=`${pageId}-content_canvas`;
                content.appendChild(contentCanvas);

                //temp_myTableCanvas.style.top=content.style.top;
                
                // content.textContent = `这是第${i}页的内容`;
               
                ////////////////////////////////////////////////////////////
                const footer = document.createElement('div');               
                footer.classList.add('footer');
                footer.id=`${pageId}-footer_div`;
                //footer.textContent = '页脚 - 页脚信息';
                document.body.appendChild(footer); 
                let W2=footer.offsetWidth;

                const footerCanvas = document.createElement('canvas');
                footerCanvas.height = 68; // Set the height of the canvas
                footerCanvas.width = W2;
                footerCanvas.id=`${pageId}-footerCanvas`;
                footer.appendChild(footerCanvas);
              
              
               
                const ctxFooter = footerCanvas.getContext('2d');
                ctxFooter.lineWidth = 1;


               
                // 必须在footer被实际添加到DOM后获取其宽度
            
               
             
                // Draw the original set of lines
                ctxFooter.beginPath();
                ctxFooter.moveTo(60, 0);              
                ctxFooter.lineTo(70, 0);
                ctxFooter.lineTo(70, 10);               

               
                ctxFooter.stroke();

                // Draw the new set of lines based on the width of the header
                ctxFooter.beginPath();
                ctxFooter.moveTo(W2 - 20, 0);
                ctxFooter.lineTo(W2 - 30, 0);
               
              
                ctxFooter.lineTo(W2 - 30, 10);
                ctxFooter.stroke();

                page.appendChild(header);
                page.appendChild(content);
                page.appendChild(footer);

                page.addEventListener('click', function() {
                    setCurrentPage(i);
                });
                canvas.appendChild(page);
            }

           

            document.querySelector('.canvas-container').addEventListener('scroll', function() {
                const scrollPosition = this.scrollTop;
                const pageHeight = document.querySelector('.page').offsetHeight + 40;
                const pageIndex = Math.floor(scrollPosition / pageHeight);
                setCurrentPage(pageIndex + 1);
            });

            function setCurrentPage(pageIndex) {
                currentPage = pageIndex;
                updatePageInfo();
            }

            function updatePageInfo() {
                const prevPage = currentPage - 1 > 0 ? currentPage - 1 : '无';
                const nextPage = currentPage + 1 <= 10 ? currentPage + 1 : '无';
               // pageInfo.textContent = `上一页: ${prevPage} 当前页: ${currentPage} 下一页: ${nextPage}`;
                const currentPageContentDiv = document.getElementById(`page-${currentPage}-content_div`);
                //currentPageContentDiv.textContent = `::::这是第${currentPage}页的内容`;
                console.log("moveto:",`page-${currentPage}-content_div`);
                

                moveCanvas(`page-${currentPage}-content_div`,currentPage);
            }

          
    }

    function moveCanvas(currentPageContentDiv,currentPage) {

     
      if(currentPage>=10)
        currentPage=9;
       //获取当前页面容器Div层
       const mainDiv = document.getElementById(`${currentPageContentDiv}`);
       //获取背景辅助画板
       const backgroundCanvas = document.getElementById('backgroundCanvas');
             backgroundCanvas.id = 'backgroundCanvas';
       //创建页面文字层画板
       const textCanvas = document.getElementById('textCanvas');
             textCanvas.id = 'textCanvas';
       //获取当前页面容器画布对像
       const myCanvas = document.getElementById("myCanvas");

       //创建背景层上下文句柄
       const bgCtx = backgroundCanvas.getContext('2d');
       //创建文字层上下文句柄
       const textCtx = textCanvas.getContext('2d');
 
   

       if(lastPageNo!=currentPage)
       {


         //console.log("lastPageNo:",lastPageNo," currentPage:",currentPage);
         if (!mainDiv.contains(myCanvas)) {
         // console.log("myCanvas:",myCanvas);
            // 将画布添加到容器中
            mainDiv.appendChild(backgroundCanvas);
            mainDiv.appendChild(textCanvas);
            mainDiv.appendChild(myCanvas);
            //console.log(" 开始添加到父亲图层");
          
            
              // 设置画布大小
              const dpr = window.devicePixelRatio || 1;
              const rect = myCanvas.getBoundingClientRect();
              backgroundCanvas.width = textCanvas.width = rect.width;// * dpr;
              backgroundCanvas.height = textCanvas.height = rect.height ;//* dpr;
              backgroundCanvas.style.left = myCanvas.offsetLeft + 'px';
              //console.log(`${currentPageContentDiv}`," myCanvas.offsetLeft + 'px':",myCanvas.offsetLeft + 'px')
              backgroundCanvas.style.top = myCanvas.offsetTop + 'px';
              textCanvas.style.left = myCanvas.offsetLeft + 'px';
              textCanvas.style.top = myCanvas.offsetTop + 'px';
              //bgCtx.scale(dpr, dpr);
              //textCtx.scale(dpr, dpr);

              // 绘制背景辅助线
              const lineHeight = 18; // 行距
              const offset = 48; // 边缘偏移
              const numLines = Math.floor(rect.height / lineHeight);
              bgCtx.lineWidth = 0.2;
              for (let i = 1; i < numLines; i++) {
                  const y = i * lineHeight + 0.2; // 在半像素位置绘制线条以增加清晰度
                  bgCtx.beginPath();
                  bgCtx.moveTo(offset, y);
                  bgCtx.lineTo(rect.width - offset, y);
                  bgCtx.stroke();
              }

              // // 绘制文字层
              // textCtx.font = "16px Arial";
              // textCtx.fillText("智能表格生产平台，为一件事提速！", 10+offset, 50); // 在文字层上输出文字

              //要在textCtx.渲染文本....这段文本可以用cellsEdit进行逐页渲染.直到完成所有的
         }

       

         lastPageNo=currentPage;
         lastPageName="page-"+currentPage;
         

       }
       else
       {
         //console.log("22222222 lastPageNo:",lastPageNo," currentPage:",currentPage);
       }
     

   
      
   }


   window.addEventListener('keydown', function(event) {
    // 检查按下的键是否是空格键（键码为32）
    if (event.keyCode === 32 && event.target === document.body) {
        event.preventDefault(); // 阻止默认行为，即页面滚动
    }
});




  $(document).ready(function() {
    

    initPages();  
    moveCanvas('page-1-content_div',1);//初始化第一页的显示
  var canvas1 = $('#canvasPopup')[0];
  var canvasContainer = document.getElementById('canvas-container');

  const menuCanvas = document.getElementById('menuCanvas');
  const menuCtx = menuCanvas.getContext('2d');

  var ctx1 = canvas1.getContext('2d');
  let myCellCanvas = document.getElementById('cellsCanvas');
  let myCanvasInitY=myCellCanvas.style.top;
  let lastScrollLeft = 0; // 用于存储上一次的水平滚动位置

  // 监听事件
    EventBus.on("customMessage", function(message) {
       // console.log("收到消息: " + message," messageType:",messageType);
       //
       //messageTypevar messageType=0;//0在渲染过程中发的消息，1在文字输入时的消息
       if(messageType===1)//当文本输入时消息类型改为0
       {


        if(editor_locked_cellRecord.rows>=0&&editor_locked_cellRecord.columns>=0)
        {
          console.log("QQ8 old:",jsonData[editor_locked_cellRecord.rows].cells[editor_locked_cellRecord.columns]," new:",textData);
          jsonData[editor_locked_cellRecord.rows].cells[editor_locked_cellRecord.columns]=textData;   
          jsonData[editor_locked_cellRecord.rows].cells[editor_locked_cellRecord.columns].content=textData.text;  
         // textData.cursorVisible=false;
         adjustTableCellHeight(jsonData,editor_locked_cellRecord.rows,message);
         hasAdjectHeight=true;
         updateTableForAdjustHeight(jsonData);
          messageType=0;//只处理一次就消费完成
          whereCallDrawTable=" message redraw!";
          redraw();//重绘表格

        }

       
    
        customMessage=0;//消费完成
       

       }
       
       
       
    });


  function addText() {
    const textContent ="This is a test\nThis should be a new paragraph\nAnd this is part of it.";// prompt("Enter new text content:");
    templateDoc.push({
        para: {
            type: "Text",
            content: textContent,
            url: "",
            rect: { left: 0, top: 0, right: 0, bottom: 0 }
        }
    });
    displayOnCanvas();
}
//增加一个段落
function addPara(m_data,m_sn,m_description)
{
 
  templateDoc.push({
      para: {
          sn:m_sn,
          type: "Para",
          data: m_data,
          content:m_description,
          url: "",
          rect: { left: 0, top: 0, right: 0, bottom: 0 }
      }
  });
 
}

function addImage() {
    const imageUrl ="../imgs/addindent.png";// prompt("Enter image URL:");
    templateDoc.push({
        para: {
            type: "Image",
            content: "Image paragraph",
            url: imageUrl,
            rect: { left: 0, top: 0, right: 0, bottom: 0 }
        }
    });
    preloadImages(displayOnCanvas);
}

function modifyItem() {
    const index = 1;//parseInt(prompt("Enter the index of the item to modify:"));
    if (index >= 0 && index < templateDoc.length) {
        const newText = "This is a test\nThis should be a new paragraph\nAnd this is part of it.";//prompt("Enter new text for this item:", templateDoc[index].para.content);
        templateDoc[index].para.content = newText;
        preloadImages(displayOnCanvas);
    }
}

function deleteItem() {
    const index = parseInt(prompt("Enter the index of the item to delete:"));
    if (index >= 0 && index < templateDoc.length) {
        templateDoc.splice(index, 1);
        preloadImages(displayOnCanvas);
    }
}



  //图像文件预加载
  function preloadImages(callback) {
    let imagesToLoad = templateDoc.filter(item => item.para.type === "Image");
    let imagesLoaded = 0;
    loadedImages = [];  // Clear previously loaded images

    if (imagesToLoad.length === 0) {
        callback();  // No images to load, proceed to rendering
        return;
    }

    imagesToLoad.forEach(item => {
        const img = new Image();
        img.onload = () => {
            loadedImages.push({ img: img, para: item.para });
            imagesLoaded++;
            if (imagesLoaded === imagesToLoad.length) {
                callback();  // All images loaded, proceed to rendering
            }
        };
        img.src = item.para.url;
    });
  }

  function addTable(m_data,m_sn,m_description)
  {
   
    templateDoc.push({ para: { sn:m_sn ,type: "table", content: m_description,tableData:m_data, url: "" , "rect": {"left": 10,"top": 0,"right": 138.0625,"bottom": 60}} });

   
  }

  function drawPara(m_paraCell,x,y,m_sn)
  {
    whereCallDrawTable=" 从drawPara调用" ;
    textData=m_paraCell;
  
    myCellCanvas = document.getElementById('cellsCanvas');
    if (myCellCanvas&&textData.text!="") {
   // console.log ("222222222222 textX:"+x," textY:"+y, " w:",m_paraCell.width,"  h:",m_paraCell.height," text:",m_paraCell.text);
    //console.log("myCellCanvas:",myCellCanvas);
    myCellCanvas.style.left=x+"px";

    myCellCanvas.style.top =y+"px";
    myCellCanvas.width=m_paraCell.width;
    myCellCanvas.height=m_paraCell.height;    
    compressStyles();    
    generateLinesData();
    textData.cursorVisible=false;   
    where_to_call="drawPara 初始预览"+whereCallDrawTable;
    renderText();	//初始预览


    upstairs_cells_height=0;
    cellsCompareData=[];//列比对数据
    current_columns_index=0;
    segmentHeight=0;
    maxTextHeight=0;
   
  where_to_call="drawPara 高度自适应初始预览"+whereCallDrawTable;

    renderText();	//高度自适应初始预览

 
    // upstairs_cells_height=0;
    // cellsCompareData=[];//列比对数据
    // current_columns_index=0;
    // segmentHeight=0;
    // maxTextHeight=0;
   


    let para_start_position=y%985;//**当前页已用空间,作为表的起始位置 .她的终点，是我的起点。
    //1.计算出当前页是否还有空间
    let remainingPageSpace=985-para_start_position; //页面容量，减去已用的量等于 剩余页面容量.
   
    pageGlobalYPosition=y;//全局Y坐标,共享变量
    drawParaCells(textData,remainingPageSpace,m_sn);//去计算单元格切割的位置, lastSegmentPosition

    remainingPageSpace=lastSegmentPosition;//重新赋值已用文本高度 


    lastPageNo=0;//强制移页y
    currentPage=Math.floor(y/985+1);
   // console.log("1557 表格翻页22:yPosition:",y,"currentPage:",currentPage,"============================"," Math.floor(y/985+1):",Math.floor(y/985+1));
     moveCanvas('page-'+currentPage+'-content_div',currentPage);//将缓存区移到下一页  

    let content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
    //console.log("1557 item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`," totalCellHeight:",totalCellHeight);
    let content_ctx_1 = content_canvas_1.getContext('2d');

    //这里会出现翻页的现像,首先要判断当前页还有多少可以绘制
   // let currentRestPageHeight=985-y%985; //变为自然段在页面的起始位置Y,当前只考虑在第一页的情形,记算出当前页还有可绘制内容的空间：currentRestPageHeight
    let restOffCurrentPageSpacing=985-y%985;

    //切面数据要从这里读回来，将restOffCurrentPageSpacing重新赋值。用循环的遍历所有数据。

      
          // console.log("QQ:1115 currentPage:",currentPage,"完成切割屏后显示切片信息:",segment_Info.length," sn:",m_sn);
           let content_canvasN_offset_Y=0;
            for (var i = 0; i < segment_Info.length; i++) 
            {

              let content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
              //console.log("1557 item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`," totalCellHeight:",totalCellHeight);
              let content_ctx_1 = content_canvas_1.getContext('2d');

            var segment = segment_Info[i];
            lastSegmentPosition=segment.height;            
            //console.log("QQ:1115 currentPage:",currentPage,"source: ",segment.dataSource," 切口 " + (i + 1) + "：","segment_index: " + segment.segment_index," offset_X: " + segment.offset_X," offset_Y: " + segment.offset_Y," width: " + segment.width,"  height: " + segment.height);
            //targetCtx.drawImage(sourceCanvas, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
            content_ctx_1.drawImage(myCellCanvas, 0, content_canvasN_offset_Y,m_paraCell.width,segment.height,m_paraCell.x, segment.offset_Y,m_paraCell.width,segment.height); // 复制到第二个画布的上
            content_canvasN_offset_Y+=segment.height;
            y=y+segment.height+30;//绘制完第一页后,Y偏移增加
            let yPosition=y;
            //console.log("QQ:1115 :段落拷贝完成y:",y%985, " pagesOffsetY:",y," 当前所在页:",currentPage );
            lastPageNo=0;//强制移页
            currentPage=Math.floor(yPosition/985+1);

            //console.log("QQ:1115 :独立自然段编写:yPosition:",yPosition,"currentPage:",currentPage,"============================"," Math.floor(yPosition/985+1):",Math.floor(yPosition/985+1));
            //console.log("QQ22: current page's yPosition:",yPosition%985);
            moveCanvas('page-'+currentPage+'-content_div',currentPage);//将缓存区移到下一页   
    
          }

          let yPosition=y;
            if(content_canvasN_offset_Y<maxTextHeight)
            {
              lastPageNo=0;//强制移页
              currentPage=Math.floor(yPosition/985+1);

              moveCanvas('page-'+currentPage+'-content_div',currentPage);//将缓存区移到下一页   
              let content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
              //console.log("1557 item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`," totalCellHeight:",totalCellHeight);
              let content_ctx_1 = content_canvas_1.getContext('2d');
  
              //console.log("QQ:1115 :独立自然段编写:yPosition:",yPosition,"currentPage:",currentPage,"============================"," Math.floor(yPosition/985+1):",Math.floor(yPosition/985+1));
              //console.log("QQ22: current page's yPosition:",yPosition%985);
           

              let restTextLineHeight=maxTextHeight-content_canvasN_offset_Y;
              //console.log("QQ:1115 :还有最后一页不足一页的自然段内容:yPosition:",yPosition,"currentPage:",currentPage,"============================"," Math.floor(yPosition/985+1):",Math.floor(yPosition/985+1));
              content_ctx_1.drawImage(myCellCanvas, 0, content_canvasN_offset_Y,800,restTextLineHeight,m_paraCell.x, 0,m_paraCell.width,restTextLineHeight); // 复制到第二个画布的上
            }
      restOffCurrentPageSpacing=lastSegmentPosition;
    //targetCtx.drawImage(sourceCanvas, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
   
    // if(restOffCurrentPageSpacing>16)//还可以绘制内容,16为字体大小.这个值要动态计算 
    // {
    //    //取消/// content_ctx_1.drawImage(myCellCanvas, 0, 0,m_paraCell.width,restOffCurrentPageSpacing,m_paraCell.x,985-restOffCurrentPageSpacing,m_paraCell.width,restOffCurrentPageSpacing); // 复制到第二个画布的上

    // 		y=y+restOffCurrentPageSpacing+30;//绘制完第一页后,Y偏移增加
    //     console.log("1557 :第一页段落拷贝完成y:",y%985, " restOffCurrentPageSpacing:",restOffCurrentPageSpacing+30," 当前所在页:",currentPage );



    //             // 将canvas内容转换为data URL
    //   var dataURL = myCellCanvas.toDataURL('image/png');

    //   // 创建一个下载链接
    //   var downloadLink = document.createElement('a');
    //   downloadLink.href = dataURL;
    //   downloadLink.download = 'canvas-image.png';

    //   // 触发下载
    //   // 使用JavaScript创建一个点击事件
    //   // 这个事件不需要用户实际点击链接
    //   downloadLink.dispatchEvent(new MouseEvent('click', {
    //     'bubbles': true,
    //     'cancelable': true,
    //     'view': window
    //   }));

    // }
  
     yPosition=y; //全局偏移增加

  
            // // 设置线条颜色
            // content_ctx_1.strokeStyle = 'green';

            // // 设置线条宽度
            // content_ctx_1.lineWidth = 5;
  
            // // 起始一条路径，或重置当前路径
            // content_ctx_1.beginPath();
  
            // content_ctx_1.moveTo(0,yPosition-50);
            // content_ctx_1.lineTo(800,yPosition-50);
  
            // // 绘制已定义的路径
            // content_ctx_1.stroke();
   
    let restParaHeight=0;//m_paraCell.height-restOffCurrentPageSpacing;//绘制了第一部分自然段,计算还有多少没有自然段的内容没有绘制完成。。
    restParaHeight=totalCellHeight-restOffCurrentPageSpacing;//是否够用
    //console.log("1557 全局yPosition:",y," restParaHeight:",restParaHeight," maxTextHeight:",maxTextHeight);
    let  nextStartY=restOffCurrentPageSpacing;
    let  totalDrawHeight=restOffCurrentPageSpacing;

    // while(restParaHeight>0)//如果
    // {
  	// 				lastPageNo=0;//强制移页
    //         currentPage=Math.floor(yPosition/985+1);

    //         console.log("1557 :独立自然段编写:yPosition:",yPosition,"currentPage:",currentPage,"============================"," Math.floor(yPosition/985+1):",Math.floor(yPosition/985+1));
    //         //console.log("QQ22: current page's yPosition:",yPosition%985);
    //         moveCanvas('page-'+currentPage+'-content_div',currentPage);//将缓存区移到下一页    
		// 				//这里的计算有问题  需要进一步处理,与检查
    //   			if(restParaHeight>985)//超过整页时,写一页
    //         {
    //           let paraStartPositionY=Math.floor(yPosition%985);
    //           //console.log("QQ8:++++++++++++++++++++++:",'page-'+currentPage+'-content_div');
    //           content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
    //           console.log("item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`);
    //           content_ctx_1 = content_canvas_1.getContext('2d');
    //           //targetCtx.drawImage(sourceCanvas, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
    //           //取消//content_ctx_1.drawImage(myCellCanvas,0,restOffCurrentPageSpacing,m_paraCell.width,985,m_paraCell.x,0,m_paraCell.width,985);
    //           totalDrawHeight=totalDrawHeight+985;
    //           restParaHeight=m_paraCell.height-totalDrawHeight;//计算还有没有未绘制的内容
    //           yPosition=yPosition+985;

    //         //     // 设置线条颜色
    //         // content_ctx_1.strokeStyle = 'Purple';

    //         // // 设置线条宽度
    //         // content_ctx_1.lineWidth = 5;
  
    //         // // 起始一条路径，或重置当前路径
    //         // content_ctx_1.beginPath();
  
    //         // content_ctx_1.moveTo(0,yPosition+975);
    //         // content_ctx_1.lineTo(800,yPosition+975);
  
    //         // // 绘制已定义的路径
    //         // content_ctx_1.stroke();
              
    //         }
    //         else
    //         {
    //            //拷贝的位置
    //         let paraStartPositionY=Math.floor(yPosition%985);
    //         console.log("1557 :自然段,将缓存区移到下一页:",'page-'+currentPage+'-content_div'," restParaHeight:",restParaHeight);
    //         content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
    //         console.log("1557 item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`);
    //         content_ctx_1 = content_canvas_1.getContext('2d');
    //         //targetCtx.drawImage(sourceCanvas, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
    //         content_ctx_1.drawImage(myCellCanvas,0,restOffCurrentPageSpacing,m_paraCell.width,restParaHeight+130,m_paraCell.x,0,m_paraCell.width,restParaHeight+130);
    //             // // 设置线条颜色
    //             // content_ctx_1.strokeStyle = 'Pink';

    //             // // 设置线条宽度
    //             // content_ctx_1.lineWidth = 5;
      
    //             // // 起始一条路径，或重置当前路径
    //             // content_ctx_1.beginPath();
      
    //             // content_ctx_1.moveTo(0,restParaHeight);
    //             // content_ctx_1.lineTo(800,restParaHeight);
      
    //             // // 绘制已定义的路径
    //             // content_ctx_1.stroke();
    //         totalDrawHeight=totalDrawHeight+restParaHeight+130;
    //         restParaHeight=m_paraCell.height-totalDrawHeight;//计算还有没有未绘制的内容
    //         yPosition=yPosition+restParaHeight;

    //         }
               
        
           

    // }

  }

}
function doSomethingAfterDelay() {
  console.log('QQ8:Do something immediately.');

  setTimeout(function() {
      console.log('QQ8::Do something after 2 seconds.');
  }, 900); // 延迟2000毫秒（2秒）执行
}
function drawTableForPage(tableData,x,y,m_sn)
{
  jsonData={};
  jsonData =tableData;
  whereCallDrawTable=" drawTableForPage 去自适应单元格高度 设置重绘 ";
  debugSN=m_sn;
  redraw(); //去自适应单元格高度
  upstairs_cells_height=0;
  cellsCompareData=[];//列比对数据
  current_columns_index=0;
  segmentHeight=0;
  maxTextHeight=0;
 
  //while(finishDrawTable===false)//等待表格绘制完成
  {
   //doSomethingAfterDelay();
  }
  whereCallDrawTable=" drawTableForPage 绘制自适应后的表格 设置重绘 ";
  redraw();//绘制自适应后的表格
  // upstairs_cells_height=0;
  // cellsCompareData=[];//列比对数据
  // current_columns_index=0;
  // segmentHeight=0;
  // maxTextHeight=0;
 
  let table_start_position=y%985;//**当前页已用空间,作为表的起始位置 .她的终点，是我的起点。
  //1.计算出当前页是否还有空间
  let restOffCurrentPageSpace=985-table_start_position; //页面容量，减去已用的量等于 剩余页面容量.

  let currentTableTop=table_start_position;//当前表格在当前页的起始Y坐标
  debugSN=m_sn;
  inMeasure=true;
  drawTableCells(jsonData,restOffCurrentPageSpace);//去计算单元格切割的位置, lastSegmentPosition
  inMeasure=false;
  //console.log("QQ:134 lastSegmentPosition:",lastSegmentPosition);
  restOffCurrentPageSpace=lastSegmentPosition;//重新赋值表格高度
  let yPosition=y;
          //将myCanvas的临时内容拷贝到textCanvas画板上
          updateTotalHeight();
          


           console.log("QQ:1115 currentPage:",currentPage,"完成切割屏后显示切片信息:",segment_Info.length," sn:",m_sn);
           let content_canvasN_offset_Y=0;
            for (var i = 0; i < segment_Info.length; i++) 
            {

              let content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
              ////*console.log("1557 item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`," totalCellHeight:",totalCellHeight);
              let content_ctx_1 = content_canvas_1.getContext('2d');

            var segment = segment_Info[i];
            lastSegmentPosition=segment.height;            
            console.log("QQ:1115 sliceType:",segment.sliceType,"currentPage:",currentPage,"source: ",segment.dataSource," 切口 " + (i + 1) + "：","segment_index: " + segment.segment_index," offset_X: " + segment.offset_X," offset_Y: " + segment.offset_Y," width: " + segment.width,"  height: " + segment.height);
            ////*targetCtx.drawImage(sourceCanvas, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
            //*content_ctx_1.drawImage(myCellCanvas, 0, content_canvasN_offset_Y,m_paraCell.width,segment.height,m_paraCell.x, segment.offset_Y,m_paraCell.width,segment.height); // 复制到第二个画布的上
            content_canvasN_offset_Y+=segment.height;
            y=y+segment.height+30;//绘制完第一页后,Y偏移增加
            let yPosition=y;
           console.log("QQ:1115 :段落拷贝完成y:",y%985, " pagesOffsetY:",y," 当前所在页:",currentPage );
            lastPageNo=0;//强制移页
            currentPage=Math.floor(yPosition/985+1);

            //console.log("QQ:1115 :独立自然段编写:yPosition:",yPosition,"currentPage:",currentPage,"============================"," Math.floor(yPosition/985+1):",Math.floor(yPosition/985+1));
            //console.log("QQ22: current page's yPosition:",yPosition%985);
            moveCanvas('page-'+currentPage+'-content_div',currentPage);//将缓存区移到下一页   
    
          }



          lastPageNo=0;//强制移页y
          currentPage=Math.floor(yPosition/985+1);

          if(moveToNextPage==true)
            {
              lastPageNo=0;
              currentPage=Math.floor(yPosition/985+1);
           
              currentPage++;
              yPosition=currentPage*985;
              //console.log("QQ:844 表格翻页:yPosition:",y,"currentPage:",currentPage,"============================"," Math.floor(y/985+1):",Math.floor(y/985+1));
              y=yPosition;


               //console.log('%cQQ:844这是红色的文字', 'color: red');
              //console.log(`%cQQ:844 ++++++++++++++++++++++++++++++ page-${currentPage}-content_canvas `,"color:red" );
              //console.log("QQ:844 item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`);
              let content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
              
              let content_ctx_1 = content_canvas_1.getContext('2d');
          
              //content_ctx_1.drawImage(myCellCanvas,  0,       0,   800,           tableTotalHeight, 48,0,0,800,985);
              //targetCtx.drawImage(sourceCanvas, sourceX, sourceY, sourceWidth,   sourceHeight,   destX, destY, destWidth, destHeight);
              content_ctx_1.drawImage(myCanvas,      0,        0,      800,     tableTotalHeight,   0,        0 ,    800,  tableTotalHeight);
            

                    
              /////////////////////////////////////////////////////////////////
              //完成第一页表格的绘制
              //console.log(" QQ844:完成第一页表格绘制");
              y=y+tableTotalHeight+60;//绘制完第一页后,Y偏移增加
              yPosition=y; //全局偏移增加
              moveToNextPage=false;
              return;
            }

          //console.log("QQ:844 表格翻页:yPosition:",y,"currentPage:",currentPage,"============================"," Math.floor(y/985+1):",Math.floor(y/985+1)," moveToNextPage:",moveToNextPage);
           moveCanvas('page-'+currentPage+'-content_div',currentPage);//将缓存区移到下一页  

        

          //console.log("QQ8: total height of table:",tableTotalHeight," 当前页表空间还有:",restOffCurrentPageSpace," 表格起始位置y:",table_start_position);

          let content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
          //console.log("item.para.type===\"table\" page-1-content_canvas:",`page-${currentPage}-content_canvas`);
          let content_ctx_1 = content_canvas_1.getContext('2d');
          //表格内容要渲染到最后的位置段落的位置上yPosition
          //console.log("-------------------------------yPosition:",yPosition);
          if(table_start_position<985)//如果表格还可以在当前页

          var  myCanvas_ctx = myCanvas.getContext('2d');
           // 设置线条颜色
           myCanvas_ctx.strokeStyle = 'black';

           // 设置线条宽度
           myCanvas_ctx.lineWidth = 2;
 
           // 起始一条路径，或重置当前路径
           //console.log("QQ:134: hasToCutCells:",hasToCutCells);
           if(hasToCutCells==true)
            {
               myCanvas_ctx.beginPath(); 
              updateTotalWidth();// 重新计算表格总宽度
              myCanvas_ctx.moveTo(tableOffsetX,lastSegmentPosition);
              myCanvas_ctx.lineTo(tableOffsetX+tableTotalWidth,lastSegmentPosition);    
              // 绘制已定义的路径
              myCanvas_ctx.stroke();
            }
          

          {
            content_ctx_1.drawImage(myCanvas,0,0, 800,restOffCurrentPageSpace,0,table_start_position,800,restOffCurrentPageSpace);
            

                    
            /////////////////////////////////////////////////////////////////
            //完成第一页表格的绘制
           // console.log(" QQ844:完成第一页表格绘制");
            y=y+restOffCurrentPageSpace+30;//绘制完第一页后,Y偏移增加
            yPosition=y; //全局偏移增加

          }
          

          //这里会出现翻页的现像,首先要判断当前页还有多少可以绘制,restOffCurrentPageSpace 是第一页绘制了多少高度的表格.
          let restParaHeight=0;
          if(tableTotalHeight<=restOffCurrentPageSpace)
          {
            restParaHeight=0;//已经绘制完成
          }
          else
          {
            restParaHeight=tableTotalHeight-restOffCurrentPageSpace; //变为自然段在页面的起始位置Y,当前只考虑在第一页的情形,记算出当前页还有可绘制内容的空间：currentRestPageHeight

          }
        

          //targetCtx.drawImage(sourceCanvas, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
        
          
        
          //剩余表格内容
          //let restParaHeight=currentRestPageHeight;//绘制了表格第一部分,计算还有多少还没有绘制的内容。
          //console.log("QQ8:全局yPosition:",y," restParaHeight:",restParaHeight," totalTableHeight:",tableTotalHeight);
          let  nextStartY=restOffCurrentPageSpace;//下一页的表格，要减去在上面的高
          let  totalDrawHeight=restParaHeight;
          while(restParaHeight>0)//如果
          {
                 

                  if(restParaHeight>985)//超过整页时,写一页
                  {

                    lastPageNo=0;//强制移页
                    currentPage=Math.floor(yPosition/985+1);
                    currentPage++;
                    //console.log("QQ:1122超过整页时,写一页表格分页:yPosition:",yPosition,"currentPage:",currentPage,"============================"," Math.floor(yPosition/985+1)+1:",Math.floor(yPosition/985+1)+1);
                    moveCanvas('page-'+currentPage+'-content_div',currentPage);//将缓存区移到下一页    

                    let subTableStartPositionY=Math.floor(yPosition%985);
                    //console.log("QQ:1122:++++++++++++++++++++++超过整页时,写一页:",'page-'+currentPage+'-content_div');
                    content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
                    //console.log("QQ:1122 item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`);
                    content_ctx_1 = content_canvas_1.getContext('2d');
                    //targetCtx.drawImage(sourceCanvas, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
                    content_ctx_1.drawImage(myCellCanvas,0,nextStartY,800,985,48,0,800,985);
                    totalDrawHeight=totalDrawHeight+985;
                    restParaHeight=tableTotalHeight-totalDrawHeight;//计算还有没有未绘制的内容

                    
                    // // 设置线条颜色
                    // content_ctx_1.strokeStyle = 'red';

                    // // 设置线条宽度
                    // content_ctx_1.lineWidth = 1;
          
                    // // 起始一条路径，或重置当前路径
                    // content_ctx_1.beginPath();
          
                    // content_ctx_1.moveTo(0,yPosition);
                    // content_ctx_1.lineTo(800,yPosition);
          
                    // // 绘制已定义的路径
                    // content_ctx_1.stroke();

                    
                  }
                  else
                  {
                    lastPageNo=0;//强制移页
                    currentPage=Math.floor(yPosition/985+1);
                    //console.log("QQ8:表格分页:yPosition:",yPosition," current page of yPosition:",yPosition%985,"currentPage:",currentPage,"============================"," Math.floor(yPosition/985+1):",Math.floor(yPosition/985+1));
                    moveCanvas('page-'+currentPage+'-content_div',currentPage);//将缓存区移到下一页    
                    //拷贝的位置
                    let paraStartPositionY=Math.floor(yPosition%985);
                    //console.log("QQ8:表格最后一页:",'page-'+currentPage+'-content_div'," paraStartPositionY:",paraStartPositionY);
                    content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
                    //console.log("item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`);
                    content_ctx_1 = content_canvas_1.getContext('2d');
                    //targetCtx.drawImage(sourceCanvas, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
                   // content_ctx_1.drawImage(myCellCanvas,0,nextStartY,m_paraCell.width,restParaHeight,m_paraCell.x,0,m_paraCell.width,restParaHeight);
                    content_ctx_1.drawImage(myCanvas,0,nextStartY, 800,restParaHeight,0,paraStartPositionY,800,restParaHeight);
                    totalDrawHeight=totalDrawHeight+restParaHeight;
                    restParaHeight=restParaHeight-totalDrawHeight;//计算还有没有未绘制的内容
                    //yPosition=yPosition+restParaHeight;

                      // // 设置线条颜色
                      // content_ctx_1.strokeStyle = 'blue';

                      // // 设置线条宽度
                      // content_ctx_1.lineWidth = 1;
            
                      // // 起始一条路径，或重置当前路径
                      // content_ctx_1.beginPath();
            
                      // content_ctx_1.moveTo(0,paraStartPositionY);
                      // content_ctx_1.lineTo(400,paraStartPositionY);
                     
            
                      // // 绘制已定义的路径
                      // content_ctx_1.stroke();


                      // content_ctx_1.beginPath();
                      // content_ctx_1.strokeStyle = 'red';
                      // content_ctx_1.lineWidth = 1;
                     
                      // content_ctx_1.moveTo(500,nextStartY);
                      // content_ctx_1.lineTo(500,nextStartY+restParaHeight);
                      // // content_ctx_1.moveTo(400,paraStartPositionY+restParaHeight-30);
                      // // content_ctx_1.lineTo(800,paraStartPositionY+restParaHeight-30);
                      // content_ctx_1.stroke();

                  }
                    
             
                

          }

          
}
 
  //文字画板层的内容渲染  
  function displayOnCanvas() {
    lastPageNo=0;//强制移页y
    currentPage=1;
    //return;////[原始还原]
    //这个是全文渲染,在渲染过程中记录内容对像的坐标索引数据,方便之后的文档编辑
    var textCanvas = document.getElementById('textCanvas');
    var textCanvas_ctx = textCanvas.getContext('2d');
    var myCanvas = document.getElementById('myCanvas');
    var myCtx = myCanvas.getContext('2d');

    let maxAscent = 0;
    let maxDescent = 0;

    let canvasOffsetLeft=textCanvas.offsetLeft;
    let canvasOffsetTop=textCanvas.offsetTop;
    var lastOffsetYinPage=0;//记录顺序段落了页面偏移

    //console.log("offsetLeft:",canvasOffsetLeft,"offsetTop:", canvasOffsetTop);
    var yPosition = 10;
    let initialLeft = 40;
    currentPage=1;

    templateDoc.forEach(item => {

        if(item.para.type ==="Para")
        {
          //1.获取自然段的宽
          //2.获取要绘制的自然段
          //3.绘制前对像赋值
          //4.返回绘制的结果:画版内容,内容高度.
          //5.赋值对像的页面,起始位置Y,内容高度.
          //console.log("1557 读取并渲染自然段",item.para.data," yPosition:",yPosition);
           let content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
           moveCanvas('page-'+currentPage+'-content_div',currentPage);//将缓存区移到下一页
    			//console.log("1557 item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`);

    			let content_ctx_1 = content_canvas_1.getContext('2d');
            /*
            // 设置线条颜色
            // content_ctx_1.strokeStyle = 'red';
            // // 设置线条宽度
            // content_ctx_1.lineWidth = 5;  
            // // 起始一条路径，或重置当前路径
            // content_ctx_1.beginPath();  
            // content_ctx_1.moveTo(0,yPosition);
            // content_ctx_1.lineTo(800,yPosition);  
            // // 绘制已定义的路径
            // content_ctx_1.stroke();
            */



          drawPara(item.para.data,0,yPosition,item.para.sn);// 参数data,x,y 这里可能要用到递归处理 直到渲染OK 每个段落都是在文本绘版上单独绘制       
         
          //console.log(`%c QQ:1115 偏差补偿:${spacingdeviation}`,"color:red");

          item.para.rect.top = yPosition;
          item.para.rect.left = initialLeft;
          item.para.rect.right = item.para.data.width; // Reset right before measure
          item.para.rect.bottom = yPosition+item.para.data.height+30+ spacingdeviation ;//假设自然段高是300
          yPosition=yPosition+item.para.data.height+30;//30表示对像行距
         
        }
        if (item.para.type === "Text") {
          textCanvas_ctx.font = '16px Arial';
          textCanvas_ctx.fillStyle = 'black';
            let lines = item.para.content.split('\n');           
            item.para.rect.top = yPosition;
            item.para.rect.left = initialLeft;
            item.para.rect.right = initialLeft; // Reset right before measuring
            lines.forEach(line => {
              
                let metrics = textCanvas_ctx.measureText(line);
                maxAscent = Math.max(maxAscent, metrics.actualBoundingBoxAscent);
                maxDescent = Math.max(maxDescent, metrics.actualBoundingBoxDescent);
                const baseLineY = yPosition +  maxAscent; // 调整y坐标，基于垂直对齐偏移

                if(yPosition>985)//段落超过当前面面
                {
                  //console.log("1557 段落超过当前页面currentPage:",currentPage);
                  moveCanvas('page-'+currentPage+'-content_div',currentPage);//将缓存区移到下一页
                  //console.log("text position y:", baseLineY-(currentPage-1)*985," lastOffsetYinPage:",lastOffsetYinPage);
                  textCanvas_ctx.fillText(line, initialLeft, baseLineY-(currentPage-1)*985);
                }
                
                else
                {
                  //console.log("1557 在当前页绘制文字:",currentPage," line Text:",line);
                  textCanvas_ctx.fillText(line, initialLeft, baseLineY);
                }
                
                yPosition += 20;
              

                item.para.rect.right = Math.max(item.para.rect.right, initialLeft + metrics.width);
                console.log("Line:",line,"left:",initialLeft,"top:",item.para.rect.top,"right:",item.para.rect.right,"bottom:",yPosition," (currentPage-1)*985:",baseLineY-(currentPage-1)*985);

               

            });
            //绘画完成所有段落之后:
            let content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
            //console.log("绘画完成所有段落之后 page-n-content_canvas:",`page-${currentPage}-content_canvas`);
            let content_ctx_1 = content_canvas_1.getContext('2d');
            content_ctx_1.drawImage(textCanvas,0,0);

            console.log("-----------------------");
            item.para.rect.bottom = yPosition;  // Correct bottom position to include the last line
            //console.log("1557: end item.para.type===\"para\" yPosition:",yPosition);


        } else if (item.para.type === "Image") {
            const imageObj = loadedImages.find(loadedImage => loadedImage.para.url === item.para.url);
            if (imageObj) {
                textCanvas_ctx.drawImage(imageObj.img, 10, yPosition);
                item.para.rect = {
                    left: 10,
                    top: yPosition,
                    right: 10 + imageObj.img.width,
                    bottom: yPosition + imageObj.img.height
                };
                yPosition += imageObj.img.height + 20;
            }
        }else if (item.para.type==="table")
        {

          //1.获取表格内容
          //2.在myCanvas上绘制表格,可以设定一个无穷大的画布,在上面一口气渲染大表.
          //3.读取从0,0 坐标上开始绘制的表格
          //4.获取表格的宽高参数
          //5.开始裁剪表格内容,从当前页面开始逐一页一页的放置图块.
          //6.回填定位信息,以便后续文档编辑.
          const currentTableData=item.para.tableData;
          //console.log("1557 读取并渲染表格",item.para.tableData);
          tableOffsetY=0;
          //console.log("QQ88: item.para.type===\"table\"::::::tableOffsetY:",tableOffsetY," yPosition:",yPosition," current page of yPosition:",yPosition%985);
          item.para.rect.top = yPosition;
          item.para.rect.left = initialLeft;
          item.para.rect.right = 800; // Reset right before measuring

          
          //在绘制表格的过程中 收集表格的长 宽  高 ；； 
          //textCanvas_ctx.clearRect(0, 0, canvas.width, canvas.height);
          //drawShadowedRect(pageX, pageY, pageWidth, pageHeight, 'rgba(0, 0, 0, 0.5)', 10, 5, 5, 'white');
         
          let content_canvas_1 = document.getElementById(`page-${currentPage}-content_canvas`);
    			//console.log("item.para.type ==\"Para\" page-1-content_canvas:",`page-${currentPage}-content_canvas`);
    			let content_ctx_1 = content_canvas_1.getContext('2d');

          drawTableForPage(currentTableData,0,yPosition,item.para.sn);
         
          //console.log("QQ8:: drawTableForPage on :",yPosition," end of yPosition:",yPosition+tableTotalHeight+32," end of yPosition at currentPage:",(yPosition+tableTotalHeight+32)%985);
         
          yPosition=yPosition+tableTotalHeight+32+offsetHeaderLine*2; 
          offsetHeaderLine=0;//表格头部偏移

          // // 设置线条颜色
          // content_ctx_1.strokeStyle = 'Blue';

          // // 设置线条宽度
          // content_ctx_1.lineWidth = 5;

          // // 起始一条路径，或重置当前路径
          // content_ctx_1.beginPath();

          // content_ctx_1.moveTo(0,yPosition%985);
          // content_ctx_1.lineTo(800,yPosition%985);

          // // 绘制已定义的路径
          // content_ctx_1.stroke();

         

          item.para.rect.bottom=yPosition;


        }


    });
    //console.log("绘制完成");
    myCellCanvas.style.display='none';
    myCanvas.style.display='none';
    
  }

  function updateCanvasPosition() {

   //console.log(" scroll ing....");
   var scrollTop = window.scrollY || document.documentElement.scrollTop;
   // 设置top为初始偏移加上页面滚动的距离

   let scrollLeft = window.scrollY || document.documentElement.scrollLeft;
   if (scrollLeft !== lastScrollLeft) {
       //console.log('水平滚动');
       // 在这里处理水平滚动的逻辑
       lastScrollLeft = scrollLeft;
   } else {
       //console.log('垂直滚动');
       // 处理垂直滚动的逻辑
   }

  
   var canvasContainer = document.getElementById('canvas-container');
  
   var containerScrollTop = canvasContainer.scrollTop;
   //console.log("Q89 offsetYYY:",containerScrollTop," initY:",myCanvasInitY," scrollTop:",scrollTop," totalOffset:",parseFloat(myCanvasInitY) + parseFloat(scrollTop) + parseFloat(containerScrollTop));
   // 设置top为页面滚动的距离加上容器内的滚动距离
   // myCellCanvas.style.top = (parseFloat(myCanvasInitY) + parseFloat(scrollTop) - parseFloat(containerScrollTop)) + 'px';
    myCellCanvas.style.display='none';
   // editor_locked_cellRecord.columns=-1;
   // editor_locked_cellRecord.rows=-1;
   isInScrolling=true;

   whereCallDrawTable=" 页面滚动 设置重绘 ";
   redraw();
  
 
}


  // 添加滚动事件监听器
window.addEventListener('scroll', updateCanvasPosition);
window.addEventListener('resize', updateCanvasPosition);
canvasContainer.addEventListener('scroll', updateCanvasPosition);

  //编辑器状态管理器
  var editorState = {
    currentObject: {
        type: null,
        id: null,
    },
    cell: {},
    textBox: {},
    image: {},
    control: {},
    dialog: {},
    updateObject: function(type, id, properties) {
        if (!this[type]) {
            console.error('Unsupported type:', type);
            return;
        }
        if (!this[type][id]) {
            this[type][id] = {};
        }
        this[type][id] = { ...this[type][id], ...properties };
        this.setCurrentObject(type, id);
    },
    setCurrentObject: function(type, id) {
        this.currentObject.type = type;
        this.currentObject.id = id;
    },
    getCurrentObject: function() {
        const { type, id } = this.currentObject;
        if (type && id && this[type] && this[type][id]) {
            return this[type][id];
        }
        return null;
    }
};

document.getElementById('lineSpacingOptionsLSS').addEventListener('click', function(e) {
  if (e.target.tagName === 'LI') {
    Array.from(this.children).forEach(child => child.classList.remove('selected'));
    e.target.classList.add('selected');
    console.log('Selected line spacing:', e.target.getAttribute('data-value'));
    document.getElementById('modalLSS').style.display = 'none';

    const cell = getCellByCoords(selectionStartX, selectionStartY);
    if(cell!=null)
    {
      cell.lineSpacing=8*parseFloat( e.target.getAttribute('data-value'));
      redraw();
    }
  }
});




// 传入边距值和行列数来绘制表格
  // 假设用户输入的边距值为10mm
  var marginTop = 10; // 上边距
  var marginBottom = 10; // 下边距
  var marginLeft = 10; // 左边距
  var marginRight = 10; // 右边距
  
  // 假设上次选中的行列数
  var lastSelectedRows = 0;
  var lastSelectedCols = 0;
/*
"cells": [
        {"content": "A1", "width": 160, "height": 40, "borderSize": 1, "showBorder": true},
*/

  function generateJsonData(rows, columns) {
    if(rows==0||columns==0)
    return;

   textData.text="";
   hadGen=false;
   lastTextData=[];
   renderText();
   var cellWidth=720/columns;
   var cellHeight=32;
   var temp_offsetX=0;
   var temp_offsetY=0;
   jsonData = [];
  for (var i = 0; i < rows; i++) {
    var row = { "cells": [] };
    for (var j = 0; j < columns; j++) {
    
      // row.cells.push({ "content": String.fromCharCode(65 + j) + (i + 1), 
      row.cells.push({ "content": " ", 
            "text":"",
            "x":temp_offsetX,"y":temp_offsetY,"width": cellWidth, "height": cellHeight, 
            "borderSize": 1, "showBorder": true ,"selected": false,
             "rowspan":0, "colspan":0,
             "parentRow":-1,"parentCol":-1,
             "mWidth":0,"mHeight":0,
             "textAlign": 0,
             "hasCheckBox":false,"checkStatus":false,
             "borderStyle":'solid',
             "borderWidth": '1px',
             "borderColor": 'black',                
             "verticalAlign":1,                 
             "indent": 0,
             "bold": false,
             "italic": false,
             "underline": false,
             "underlineColor": "rgb(255, 0, 0)",
             "backgroundColor": "transparent",
             "underlineStyle": "wavy",
             "strikethrough": false,
             "color": "rgb(0, 0, 0)",
            fontStyles: [
              { start: 0, end: 2, font: "黑体"},
            ],
            "fontSize": [
                    { font:"宋体"}
                ],           
            "underlineColor": [
                { }
            ], 
            "fontColor": [
                {  }
            ],                     
            "italic": [ //斜体属性
                {  }
            ],
            "bold": [ // 加粗
                { }
            ],
            "underline": [ // 下划线
                { }
            ],
            "underlineStyle":[ // 下划线
                { }
            ],
            "lineThrough": [ // 删除线
                {  }
            ],
            "background": [ // 背景色
                {  }
            ],
            "firstLineIndent": 2,
            "lineSpacing": 15, // 行间距    
            "horizontalAlign": 'left', //水平对齐方式
            "verticalAlign": 'top',// 垂直对齐方式
            "firstLineIndent": 2,
            "lineSpacing": 15,
            "horizontalAlign": "left",
            "cells_selectionStart":0,
            "cells_selectSecond":0, 
            "cells_selectionEnd":0,
            "maxHeight":16,
            "minHeight":16,
            "cursorVisible":false
           


      
      });
      temp_offsetX+=cellWidth;  
    }
    temp_offsetY+=cellHeight
    temp_offsetX=0;
    jsonData.push(row);
  }
  return jsonData;
}

 //绘制下划线：style 0 为直线，1为波浪线，2为双行线
 function drawUnderline(ctx, x, y, width, color, style) {
    ctx.beginPath();
    ctx.strokeStyle = color;
    if (style === 'straight') {
        ctx.moveTo(x, y);
        ctx.lineTo(x + width, y);
    } else if (style === 'wavy') {
        let amplitude = 2;
        let frequency = 5;
        let x1 = x;
        let y1 = y;
        ctx.moveTo(x1, y1);
        for (let i = 0; i < width; i += frequency) {
            ctx.lineTo(x1 + i, y1 + ((i % (frequency * 2)) === 0 ? amplitude : -amplitude));
        }
    } else if (style === 'double') {
        ctx.moveTo(x, y - 2);
        ctx.lineTo(x + width, y - 2);
        ctx.moveTo(x, y + 2);
        ctx.lineTo(x + width, y + 2);
    }
    ctx.stroke();
    }

 
function drawTextInRect(ctx, text, cell_x, cell_y, maxWidth,maxHeight , align, displayMode, verticalAlign, font, fontSize, indent, color, underline, strikethrough, italic, underlineColor, underlineStyle, backgroundColor, lineSpacing,bold) {
 return ;

 var fontStyle = (italic == 1 ? "italic " : "") + (bold == 1 ? "bold " : "");
 ctx.font = fontStyle + fontSize + 'px ' + font;
 ctx.fillStyle = color; // 设置文本颜色


  //////////////////////////////////////////////////////////////////////////////////////
    // 估计文本的高度
    // 注意: 这是一个简单的估计方法，可能不适用于所有字体和情况
     // 使用measureText()测量文本的宽度
     var metrics = ctx.measureText(text);
    var width = metrics.width;
    var height = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;

    // 输出文本的宽度和估计的高度
    console.log("A1: Text width: " + width + "px"  );
    console.log("A1: Estimated text height: " + height);

    // 可选: 在Canvas上标出文本区域
    //ctx.strokeRect(drawX, y - metrics.actualBoundingBoxAscent, width, height);
    ///////////////////////////////////////////////////////////////////////////////////////

 var lineHeight=height;
 var indentSize = ctx.measureText(' ').width * indent; // 计算缩进的像素大小
 var lines = displayMode == 1 ? [] : [''];
 var currentLine = '';

 var isFirstLine = true;
 var y=0;
 var x=0;

 if (displayMode == 1) {
     for (let i = 0; i < text.length; i++) {
         var char = text[i];
         var testLine = currentLine + char;
         var metrics = ctx.measureText(testLine);
         var currentLineWidth = maxWidth - (isFirstLine ? indentSize : 0); // 首行减去缩进大小
         if (metrics.width > currentLineWidth && i > 0) {
             lines.push(currentLine);
             currentLine = char;
             isFirstLine = false;
         } else {
             currentLine = testLine;
         }
     }
     lines.push(currentLine);
 } else {
     // 单行模式下，考虑首行缩进
     var singleLineText = text.slice(0, maxWidth / ctx.measureText(' ').width - 3 - indent) + '...';
     lines = [singleLineText];
 }

 var totalHeight = lines.length * lineHeight;
 if (verticalAlign == 1) {
     y = (maxHeight - totalHeight) / 2;   //垂直居中
 } else if (verticalAlign == 2) {
     y = maxHeight - totalHeight;
 } // 顶部对齐不需要调整y
 else{
    y=lineHeight/2;
 }


 y=cell_y+y+2;
 canvasOffset = $('#myCanvas').offset(); 
 var cellStartX = canvasOffset.left+tableOffsetX;
var  cellStartY = canvasOffset.top+tableOffsetY;


 lines.forEach(function(line, index) {

  console.log("A1 参数 Y:"+(y-tableOffsetY)+ "  verticalAlign:"+verticalAlign +" totalHeight:"+totalHeight+" maxHeight:"+maxHeight+ "  lines.length:"+lines.length+ " lineHeight:"+lineHeight+" tableOffset:"+tableOffsetY+" real y:"+y+" line:"+line+" textAlign:"+align+ " underline:"+underline+" fontSize:"+fontSize);
 var words = line.split(' ');
 var lineY = y + index * (lineHeight + lineSpacing);
 // 设置背景颜色
 if (backgroundColor != 'transparent') {
 ctx.fillStyle = backgroundColor;
 var textWidth = ctx.measureText(text).width;
 var backgroundHeight = lineHeight+5;
 var backgroundWidth = textWidth;
 var backgroundX = x+cell_x;
 var backgroundY = y - fontSize+5; // 调整背景位置以适配文本
 ctx.fillRect(backgroundX, backgroundY, backgroundWidth, backgroundHeight+lineSpacing);
 ctx.fillStyle = color; // 重置为文本颜色
 }


 if (align == 3 && words.length > 1) { // 分散对齐
     var totalWidth = words.reduce(function(sum, word) {
         return sum + ctx.measureText(word).width;
     }, 0);
     var remainingSpace = maxWidth - totalWidth;
     var spaceWidth = remainingSpace / (words.length - 1);
     var currentPosition = x;
     
     words.forEach(function(word, wordIndex) {
         ctx.fillText(word, currentPosition, y);
         currentPosition += ctx.measureText(word).width + spaceWidth;
     });
 } 
 else {

     var lineWidth = ctx.measureText(line).width;
     var drawX = x + (index == 0 ? indentSize : 0);
     if (align == 1 ) {
         drawX += (maxWidth - lineWidth) / 2;
     } else if (align == 2 ) {
         drawX += maxWidth - lineWidth;
     }
     drawX=drawX+cell_x;
     ctx.fillText(line, drawX, y);
     console.log("A1 参数 Y:"+(y-tableOffsetY)+ "  verticalAlign:"+verticalAlign +" totalHeight:"+totalHeight+" maxHeight:"+maxHeight+ "  lines.length:"+lines.length+ " lineHeight:"+lineHeight+" drawX:"+drawX);

   

 }

 //下划线绘制逻辑
 if (underline == 1) {
     var underlineY = y + lineHeight/2; // 稍微在文字下方一点
     var textWidth = ctx.measureText(line).width;
     drawUnderline(ctx, drawX, underlineY, textWidth, underlineColor, underlineStyle);
 }

    // 删除线的绘制逻辑
 if (strikethrough == 1) {     
     var strikethroughY = y -lineHeight/4+2 ; // 计算删除线位置，这里的计算方法仅为示例，可能需要调整
     var textWidth = ctx.measureText(line).width;
     drawUnderline(ctx, x+cell_x, strikethroughY, textWidth, underlineColor, underlineStyle);
 }

 y += lineHeight+lineSpacing;

});      

}

	
function drawRoundedRect(ctx, x, y, width, height, radius, fillStyle) {
  ctx.fillStyle = fillStyle;
  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.arcTo(x + width, y, x + width, y + height, radius);
  ctx.arcTo(x + width, y + height, x, y + height, radius);
  ctx.arcTo(x, y + height, x, y, radius);
  ctx.arcTo(x, y, x + width, y, radius);
  ctx.closePath();
  ctx.fill();
}

function highlightButton(buttonId, state) {
  const button = document.getElementById(buttonId);
  if (button) { // 确保找到了按钮
    if (state === 1) {
      // 添加高亮样式
      button.classList.add('button-highlight');
    } else if (state === 0) {
      // 移除高亮样式，恢复默认状态
      button.classList.remove('button-highlight');
    }
  }
}


highlightButton('splitCells', 1);

// Menu Drawing function
function drawMenu(x, y) {
  isIntoMenuSelection=1;
  // Set the position of the menu
  $(menuCanvas).css({top: y, left: x}).show();

  // Draw the rounded rectangle
  menuCtx.fillStyle = 'rgba(255, 255, 255, 0.9)';
  menuCtx.shadowColor = 'rgba(0, 0, 0, 0.5)';
  menuCtx.shadowBlur = 1;
  menuCtx.fillRect(5, 5, 140, 90);

  // Draw the title bar
  menuCtx.fillStyle = '#003366';
  menuCtx.fillRect(5, 5, 140, 20);

  // Draw the title text
  menuCtx.fillStyle = 'white';
  menuCtx.font = 'bold 14px Arial';
  menuCtx.fillText('提示', 10, 20);

  // Draw the menu items
  menuCtx.fillStyle = '#003366';
  menuCtx.font = '12px Arial';
  menuCtx.fillText('合并单元格', 10, 50);
  menuCtx.fillText('取消', 10, 80);
}

// Menu item interaction
$(menuCanvas).on('mousemove', function(e) {
  const rect = menuCanvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // Redraw the menu (which clears previous highlights)
  drawMenu(parseInt($(menuCanvas).css('left')), parseInt($(menuCanvas).css('top')));

  // Define menu item bounds
  const mergeCellsItemBounds = { top: 30, bottom: 50 };
  const cancelItemBounds = { top: 60, bottom: 80 };

  // Highlight and re-draw text for 'Merge Cells' item
  if (y > mergeCellsItemBounds.top && y < mergeCellsItemBounds.bottom) {
    // Highlight background
    menuCtx.fillStyle = 'lightblue';
    menuCtx.fillRect(5, 35, 140, 20);
    // Re-draw text
    menuCtx.fillStyle = '#003366';
    menuCtx.fillText('合并单元格', 10, 50);
  }

  // Highlight and re-draw text for 'Cancel' item
  if (y > cancelItemBounds.top && y < cancelItemBounds.bottom) {
    // Highlight background
    menuCtx.fillStyle = 'lightblue';
    menuCtx.fillRect(5, 65, 140, 20);
    // Re-draw text
    menuCtx.fillStyle = '#003366';
    menuCtx.fillText('取消', 10, 80);
  }
});
// Event listener for table right-clicks
$(myCanvas).on('contextmenu', function(e) {
  e.preventDefault(); // Prevent the default context menu from showing

  const rect = myCanvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  // Check if we clicked inside a cell
 //这里绘制右键菜单 
    drawMenu(x, y);
  
});



function hideMenu() {
  isIntoMenuSelection=0;//进入菜单选择状态
  menuCanvas.style.display = 'none';
}



  function drawTableFromJson(jsonData) {
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  canvas.width = jsonData[0].cells.reduce((acc, cell) => acc + cell.width, 0);
  canvas.height = jsonData.length * jsonData[0].cells[0].height;
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  var currentX = 0;
  var currentY = 0;

  


  jsonData.forEach(function(rowData, rowIndex) {
    currentX = 0;
    rowData.cells.forEach(function(cell) {
      if (cell.showBorder) {
        ctx.strokeRect(currentX, currentY, cell.width, cell.height);
      }
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";
      ctx.fillText(cell.content, currentX + cell.width / 2, currentY + cell.height / 2);
      currentX += cell.width;
    });
    currentY += rowData.cells[0].height;
  });
}

 // Function to draw the icon on the canvas
 function drawIcon(x, y) {
    if (iconLoaded && iconVisible) {
      // Clear the canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      
      // Draw the icon
      ctx.drawImage(icon, x - icon.width / 2, y - icon.height / 2);
    }
  }

  // Function to draw the grid
  function drawGrid() {
    ctx1.clearRect(0, 0, canvas1.width, canvas1.height);
    ctx1.beginPath();
    for (var row = 0; row < rows; row++) {
      for (var col = 0; col < columns; col++) {
        ctx1.rect(
          gridSpacing + col * (gridSize + gridSpacing),
          gridSpacing + row * (gridSize + rowSpacing),
          gridSize,
          gridSize
        );
      }
    }
    ctx1.strokeStyle = gridColor;
    ctx1.stroke();
  }



  // Function to highlight squares
  function highlightSquares(x, y) {
    var colEnd = Math.floor(x / (gridSize + gridSpacing));
    var rowEnd = Math.floor(y / (gridSize + rowSpacing));

    colEnd = colEnd >= columns ? columns - 1 : colEnd;
    rowEnd = rowEnd >= rows ? rows - 1 : rowEnd;

    for (var row = 0; row <= rowEnd; row++) {
      for (var col = 0; col <= colEnd; col++) {
        ctx1.fillStyle = highlightColor;
        ctx1.fillRect(
          gridSpacing + col * (gridSize + gridSpacing),
          gridSpacing + row * (gridSize + rowSpacing),
          gridSize,
          gridSize
        );
      }
    }



    // Display the selection info
    $('#showInfo').text('Selected Rows: ' + (rowEnd + 1) + ', Columns: ' + (colEnd + 1));
    
    return { rows: rowEnd + 1, columns: colEnd + 1 };
  }
  
 

// 初始化单元格对象
editorState.updateObject('cell', 'cell1', {
    borderStyle: 'solid',
    borderWidth: '1px',
    borderColor: 'black',
    textAlign: 'center',
    verticalAlign: 'middle'
});
  
     // 监听按钮点击事件
     document.getElementById('show_insert_table').addEventListener('click', function(event) {
        const button = event.currentTarget;
        const canvas = document.getElementById('canvasPopup');
        const buttonRect = button.getBoundingClientRect();
    
        // 设置 canvas 位置在按钮的左下方
        canvas.style.top = buttonRect.bottom + window.scrollY + 'px'; // 添加滚动偏移
        canvas.style.left = buttonRect.left + window.scrollX + 'px'; // 添加滚动偏移
    
        // 切换 canvas 的显示状态
        canvas.style.display = (canvas.style.display === 'block') ? 'none' : 'block';
    
        // 绘制格子，如果 canvas 已显示
        if (canvas.style.display === 'block') {
         // drawGrid(canvas);
         drawGrid(); // Initial grid draw
        }
      }); 
 // Mousedown event to confirm selection and hide the first layer
  

 function drawTableOnLayer2WithMargins(rows, cols, marginTop, marginBottom, marginLeft, marginRight) {
    var canvas2 = document.getElementById('myCanvas');
    var ctx2 = canvas2.getContext('2d');
    var a4WidthPixels = 793; // A4宽度，单位为像素
    var a4HeightPixels = 1122; // A4高度，单位为像素
  
    // 边距转换为像素，这里假设边距是以毫米为单位输入的
    var marginTopPixels = marginTop * 3.78;
    var marginBottomPixels = marginBottom * 3.78;
    var marginLeftPixels = marginLeft * 3.78;
    var marginRightPixels = marginRight * 3.78;
  
    // 计算可用于表格的宽度和高度
    var usableWidth = a4WidthPixels - marginLeftPixels - marginRightPixels;
    var usableHeight = 40*3.78*rows;//a4HeightPixels - marginTopPixels - marginBottomPixels;
  
    // 根据可用宽度和高度计算单元格的宽度和高度
    var cellWidth = usableWidth / cols;
    var cellHeight = 40;//usableHeight / rows;
  
    // 清除之前的绘制
    ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
  
    // 开始绘制表格
    ctx2.beginPath();
    for (var row = 0; row < rows; row++) {
      for (var col = 0; col < cols; col++) {
        ctx2.rect(marginLeftPixels + col * cellWidth, marginTopPixels + row * cellHeight, cellWidth, cellHeight);
      }
    }
    ctx2.strokeStyle = 'black';   // 设置线条颜色
    ctx2.stroke();                // 绘制表格线条
  }

    checkedBoxImage = new Image();
    checkBoxImage = new Image();

    // 定义一个创建图片加载Promise的函数，接受图片对象和图片路径作为参数
    function loadImage(image, src) {
        return new Promise((resolve, reject) => {
            $(image).on('load', resolve).on('error', () => reject(`Failed to load image at ${src}`));
            image.src = src;
        });
    }

    // 使用Promise.all等待所有图片都加载成功
    Promise.all([
        loadImage(checkedBoxImage, 'imgs/checked_box.png'),
        loadImage(checkBoxImage, 'imgs/check_box.png')
    ]).then(() => {
        console.log('所有图片加载成功');
        // 所有图片加载成功后的操作
        whereCallDrawTable=" 所有图片加载成功 设置重绘 ";
       // redraw();
    }).catch((error) => {
        console.log(error); // 打印出失败的图片
        // 处理图片加载失败的情况
    });


    var selectFontColor_colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF', '#000000', '#FFFFFF',
              '#C0C0C0', '#808080', '#800000', '#808000', '#008000', '#800080', '#008080', '#000080',
              '#FFA500', '#A52A2A', '#FFFFF0', '#F0E68C', '#6495ED', '#DC143C', '#FFD700', '#ADFF2F'];

  
    var selectFontColor_dialog = $('<div></div>').appendTo('body').hide();
    for(var i = 0; i < selectFontColor_colors.length; i++) {
        $('<div></div>')
            .addClass('selectFontColor_color-button')
            .css('background-color', selectFontColor_colors[i])
            .appendTo(selectFontColor_dialog)
            .click(function() {
                var color = $(this).css('background-color');
                console.log("A2 selectFontColor:"+color);
                selectFontColor_dialog.dialog('close');

                const cell = getCellByCoords(selectionStartX, selectionStartY);
                if(cell!=null)
                {
                  
                 

                  updateSelectedTextColor(color);
                    compressStyles();                
                    generateLinesData();  
                    cell.color=textData.color;
                    whereCallDrawTable=" selectFontColor_colors 设置重绘 ";
                  redraw();
                  return;
                }
               
            });
    }

    selectFontColor_dialog.dialog({
        autoOpen: false,
        title: '选择颜色'
    });

    $('#set_fontcolor').click(function(e) {
        var x = e.pageX;
        var y = e.pageY;

        selectFontColor_dialog.dialog("option", "position", {
            my: "left top",
            at: "left+" + x + " top+" + y,
            of: window,
            collision: "fit"
        });

        selectFontColor_dialog.dialog('open');
    });

 // 字体选项数组
      // var fontOptions = [
      //     "思源黑体",
      //     "思源宋体",
      //     "思源柔黑",
      //     "思源真黑",
      //     "方正仿宋简体",
      //     "方正黑体简体"
      // ];

      var fontOptions = [
          "黑体",
          "宋体",
          "仿宋",
          "楷体",
          "方正仿宋简体",
          "方正黑体简体"
      ];

      // 将字体选项添加到下拉框中
      $.each(fontOptions, function(index, font) {
          $('#fontSelector').append('<option value="' + font + '">' + font + '</option>');
      });

      $('#fontSelector').change(function() {
          var selectedFont = $(this).val();
          console.log("A1 当前选中的字体是：" + selectedFont);

          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            updateStyleProperty(textData.fontStyles, selectedFont, 'font');
            cell.fontStyles=textData.fontStyles;
            console.log("A1: cell.selectFont click: 1"+cell.font);
          }
          whereCallDrawTable=" fontSelector 设置重绘 ";
          redraw();
          return;
          // 修改页面元素的字体样式
          $('body').css('font-family', selectedFont);
      });
      


        // 常用字体大小数组
  var fontSizes = [8, 12, 14, 16, 18, 20, 24, 32, 48];

// 将字体大小选项添加到下拉框中
$.each(fontSizes, function(index, size) {
    $('#fontSizeSelector').append('<option value="' + size + '">' + size + '</option>');
});



$('#fontSizeSelector').change(function() {
        
    var selectedSize = $('#fontSizeSelector').val();
    console.log("A3 当前选中的字体大小是：" + selectedSize);
    const cell = getCellByCoords(selectionStartX, selectionStartY);
        if(cell!=null)
        {
         
         
          //console.log("A3: 加一后 cell incFontSize: "+cell.fontSize);

           if(selectedSize>164)
           selectedSize=164;

           

           textData=cell;
           textData.text=cell.content;

           updateSelectedTextSize(selectedSize);
           cell.fontSize=textData.fontSize;
         


          // editer_locked_selectChars.start=textData.cells_selectionStart;
          // editer_locked_selectChars.end=textData.cells_selectionEnd
         
          
          console.log("A3: cell.selectedSize click: 1"+cell.selectedSize);
        }
        whereCallDrawTable=" fontSizeSelector 设置重绘 ";
        redraw();
        return;
      });


     /*
    "text-align":0
	   单元格对齐方： 
     0 水平左对齐   1 水平居中  2 水平右对齐   3 垂直顶部对齐  4 垂直居中对齐  5 垂直底部对齐 6 
    */
    $('.menu-item').click(function(event) {
        var action = $(this).data('action'); // 使用jQuery的.data()方法获取data-action值
        console.log('Clicked button action:', action);

        if(action=="left_align")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.textAlign=0;
            console.log("A1: align click: 0"+cell.content);
            cell.horizontalAlign="left";
          //////////////////////////////
              renderText();
          }
          whereCallDrawTable=" left_align 设置重绘 ";
          redraw();
          return;
        }

        if(action=="midd_align")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.textAlign=1;
            cell.horizontalAlign="center";
            console.log("A1: align click: 1"+cell.content);
            renderText();
          }
          whereCallDrawTable=" center设置重绘 ";
          redraw();
          return;
        }

        if(action=="right_align")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.textAlign=2;
            cell.horizontalAlign="right";
            console.log("A1: align click: 2"+cell.content);
          }
          renderText();
          whereCallDrawTable=" 段落right_align设置重绘 ";
          redraw();
          return;
        }

        if(action=="justify_align")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.textAlign=3;
            console.log("A1: align click: 3"+cell.content);
          }
          whereCallDrawTable=" 段落两边对齐设置重绘 ";
          redraw();
          return;
        }

        if(action=="lineheight") //行高
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            const modal = document.getElementById('modalLSS');
            const modalWidth = modal.offsetWidth;

            // 计算点击位置和居中调整
            let x = event.pageX - modalWidth / 2;


            // 保证对话框不超出左侧或右侧边界
            x = Math.max(10, x); // 确保对话框不会贴近窗口左边缘
            x = Math.min(x, document.body.clientWidth - modalWidth - 10); // 确保对话框不会贴近窗口右边缘
            console.log("x:",x);
            modal.style.left = `${x}px`;
            modal.style.top = `${event.pageY + 10}px`; // 稍微偏下以避免挡住点击的元素
            modal.style.display = 'block';

            setDefaultSelection("1.5"); // Set default selected line spacing
          }
          
          //cell.lineSpacing=8;//要读取一下单元格的默认行距
          whereCallDrawTable=" 段落行距设置重绘 ";
          redraw();
          return;
        }


        if(action=="valign_top")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.verticalAlign=0;
            cell.verticalAlign="top";
            console.log("A1: click: 0"+cell.content);
          }
          redraw();
          return;
        }

        if(action=="valign_midd")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.verticalAlign=1;
            cell.verticalAlign="middle";
            console.log("A1: click: 1"+cell.content);
          }
          whereCallDrawTable=" 字体垂直居中设置重绘 ";
          redraw();
          return;
        }

        if(action=="valign_bottom")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            cell.verticalAlign=2;
            cell.verticalAlign="bottom";
            console.log("A1: click: 0"+cell.content);
          }
          whereCallDrawTable=" 字体底部对齐重绘 ";
          redraw();
          return;
        }


        if(action=="addindent")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            let myIndent=cell.indent+1;
            cell.indent=myIndent;
            console.log("A1: indent click: 1"+cell.content);


            updateSelectedFirstLineIndent(myIndent);
            compressStyles();                
            generateLinesData();

          }
          whereCallDrawTable=" 字体缩进1设置重绘 ";
          redraw();
          return;
        }

        if(action=="minusindent")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            if(cell.indent>0)
            {

              let myIndent=cell.indent-1;
              cell.indent=myIndent;
              console.log("A1: indent click: 1"+cell.content);
  
              
              updateSelectedFirstLineIndent(myIndent);
              compressStyles();                
              generateLinesData();

            }
           

           
        
            console.log("A1: indent click: 2"+cell.content);
          }
          whereCallDrawTable=" 字体缩进设置重绘 ";
          redraw();
          return;
        }

        if(action=="incFontSize")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          let   myFontSize=16;
          if(cell!=null)
          {
            console.log("A3: cell incFontSize: "+cell.fontSize);

            myFontSize=textData.maxHeight;
            if(myFontSize<164)
            myFontSize= myFontSize+1;
            //console.log("A3: 加一后 cell incFontSize: "+cell.fontSize);

             if(myFontSize>164)
             myFontSize=164;

             

             textData=cell;
             textData.text=cell.content;

             updateSelectedTextSize(myFontSize);
             cell.fontSize=textData.fontSize;
           
             console.log("A3: incFontSize :"+myFontSize);
          }
          whereCallDrawTable=" 字体增大设置重绘 ";
          redraw();
          return;
        } 

       if(action=="minFontSize")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          let   myFontSize=16;
          if(cell!=null)
          { 
           
            myFontSize=textData.minHeight;

            console.log("A3: cell minFontSize: "+myFontSize);
            if(myFontSize>1)
            myFontSize=myFontSize-1;
            textData=cell;
            textData.text=cell.content;

            updateSelectedTextSize(myFontSize);
            cell.fontSize=textData.fontSize;
            console.log("A3: minFontSize click: 2 "+myFontSize);
          }
          whereCallDrawTable=" 字体缩小设置重绘 ";
          redraw();
          return;
        }

        

        if(action=="setBold")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            
            
            console.log("A1: cell.bold click: 1"+cell.content);
           // textData.bold=cell.bold;
            boldButtonStatus=!boldButtonStatus;
            updateSelectedBold(boldButtonStatus);
            cell.bold=textData.bold;
            compressStyles();                
            generateLinesData(); 


          }
          whereCallDrawTable=" 字体加粗设置重绘 ";
          redraw();
          return;
        }




        if(action=="italicOn")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            
            // cell.italic=!cell.italic;
            italicButtonStatus=!italicButtonStatus;
            updateSelectedItalic(italicButtonStatus);
                    compressStyles();                
                    generateLinesData();  
                    cell.italic=textData.italic;
            console.log("A1: cell.italic click: 1"+cell.content);
          }
          whereCallDrawTable=" 斜体设置重绘 ";
          redraw();
          return;
        }

        if(action=="underLine")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            underlineButtonStatus=!underlineButtonStatus;
            updateSelectedUnderLine(underlineButtonStatus);
            compressStyles();                
            generateLinesData();  

            cell.underline=textData.underline;
            // cell.strikethrough=false;
            console.log("A1: cell.underline click: 1"+cell.content+ " hasUnderLine:"+cell.underline);
          }
          whereCallDrawTable=" 下划线设置重绘 ";
          redraw();
          return;
        }

        if(action=="deleteline")
        {
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            
            strikethroughButtonStatus=!strikethroughButtonStatus;
            updateSelectedUnderLine(true);
          
            // cell.strikethrough=!cell.strikethrough;
            // cell.underline=false;
            console.log("A1: cell.strikethrough click: 1"+cell.content+ " has strikethrough:"+cell.strikethrough);
          }
          whereCallDrawTable=" 删除线设置重绘 ";
          redraw();
          return;
        }

        if(action=="sign-up")
        {

          // 当你想让上层canvas接收事件，下层canvas不接收事件
         
          // 如果你之后需要让下层canvas重新接收事件
     
          document.getElementById('main_canvas').style.pointerEvents='none';
          document.getElementById(lastPageName).style.pointerEvents='none';

          document.getElementById('myCanvas').style.pointerEvents = 'none';
          document.getElementById('page-1-content_div').style.pointerEvents='none';
          // 如果你之后需要让下层canvas重新接收事件,还是要分开的
          document.getElementById('cellsCanvas').style.pointerEvents = 'none';
          document.getElementById('textCanvas').style.pointerEvents = 'auto';

         


          console.log(" sign-up------------------------> ");
          allowEditCell=false;
          whereCallDrawTable=" sin-up重绘 ";
          redraw();
          return;
        }




        $('#selectLineColor_openDialog').click(function(event) {
        var dialog = $('#selectLineColor_dialog');
        var x = event.clientX;
        var y = event.clientY;
        var dialogWidth = dialog.outerWidth();
        var dialogHeight = dialog.outerHeight();
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();

        // Adjust if the dialog goes beyond the right edge
        if (x + dialogWidth > windowWidth) {
          x -= (x + dialogWidth - windowWidth);
        }

        // Adjust if the dialog goes beyond the bottom edge
        if (y + dialogHeight > windowHeight) {
          y -= (y + dialogHeight - windowHeight);
        }

        // Adjust if the dialog goes beyond the left edge
        if (x < 0) {
          x = 0;
        }

        // Adjust if the dialog goes beyond the top edge
        if (y < 0) {
          y = 0;
        }

        dialog.css({'left': x + 'px', 'top': y + 'px', 'display': 'block'});
      });



      $('#selectLineColor_dialog').click(function(event) {
        if ($(event.target).is('button')) {
          console.log("A1 buttonID:"+event.target.id);
          $('#selectLineColor_dialog').hide();

            const cell = getCellByCoords(selectionStartX, selectionStartY);
            if(cell!=null)
            {
              
            
              let mycolor="rgb(0, 0, 0)";
              if(event.target.id=="selectLineColor_black")
              mycolor='rgb(0, 0, 0)';
              if(event.target.id=="selectLineColor_green")
              mycolor='rgb(0, 255, 0)';
              if(event.target.id=="selectLineColor_red")
              mycolor='rgb(255, 0, 0)';
              if(event.target.id=="selectLineColor_noColor")
              mycolor='transparent';

              updateSelectedUnderLine(true);                          
              updateSelectedUnderLineColor(mycolor);
              compressStyles();                
              generateLinesData();  
              cell.underlineColor=textData.underlineColor;

              console.log("A1: cell.underlineColor click: 1"+cell.content+ " underlineColor:"+cell.underlineColor);
            }
            whereCallDrawTable=" underlineColor下划线样式设置重绘 ";
            redraw();
            return;

        }
      });



        if(action=="backgroundColor")
        {
         
          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null)
          {
            var myGBColor="transparent";
            
           backgroundColorButtonStatus=!backgroundColorButtonStatus;
           myGBColor=backgroundColorButtonStatus?myGBColor:'black';


           updateSelectedGBColor(myGBColor);
           compressStyles();                
           generateLinesData(); 
           cell.background=textData.background; 
          // renderText();
        
             
   					
            console.log("A1: cell.underline click: 1"+cell.content+ " backgroundColor:"+myGBColor);
          }
          whereCallDrawTable=" 下划线颜色设置重绘 ";
          redraw();
          return;
        }

 

    });

    $('#selectLineStyle_openDialog').click(function(event) {
        var dialog = $('#selectLineStyle_dialog');
        var x = event.clientX;
        var y = event.clientY;
        var dialogWidth = dialog.outerWidth();
        var dialogHeight = dialog.outerHeight();
        var windowWidth = $(window).width();
        var windowHeight = $(window).height();

        // Adjust if the dialog goes beyond the right edge
        if (x + dialogWidth > windowWidth) {
          x -= (x + dialogWidth - windowWidth);
        }

        // Adjust if the dialog goes beyond the bottom edge
        if (y + dialogHeight > windowHeight) {
          y -= (y + dialogHeight - windowHeight);
        }

        // Adjust if the dialog goes beyond the left edge
        if (x < 0) {
          x = 0;
        }

        // Adjust if the dialog goes beyond the top edge
        if (y < 0) {
          y = 0;
        }

        dialog.css({'left': x + 'px', 'top': y + 'px', 'display': 'block'});
      });

      $('#selectLineStyle_dialog').click(function(event) {
        if ($(event.target).is('button')) {
          console.log(event.target.id);
          var mySelectLineStyle="";

  

          if(event.target.id=="selectLineStyle_straightLine")
          {
            console.log("style:0");
            mySelectLineStyle='straight';

          }
          if(event.target.id=="selectLineStyle_doubleLine")
          {
            console.log("style:1");
            mySelectLineStyle='double';

          }
          if(event.target.id=="selectLineStyle_wavyLine")
          {
            console.log("style:2");
            mySelectLineStyle='wavy';

          }

          const cell = getCellByCoords(selectionStartX, selectionStartY);
          if(cell!=null&&mySelectLineStyle!="")
          {
                    updateSelectedUnderLine(true);
                    updateSelectedUnderLineStyle(mySelectLineStyle);
                    cell.underlineStyle=textData.underlineStyle;
            
            // cell.underlineStyle=mySelectLineStyle;            
            // console.log("A1: cell.bold click: 1"+cell.content);
          }


          $('#selectLineStyle_dialog').hide();
          whereCallDrawTable=" 下划线设置重绘 ";
          redraw();
          return;
        }
      });
   

    var cellData = {
        width: 200,
        height: 50,
        borders: {
            top: 'solid',
            right: 'solid',
            bottom: 'solid',
            left: 'solid'
        }
    };

    function updateCellStyle() {
        var cellEdge = $('#cell-edge');
        cellEdge.css({
            'border-top': '3px ' + cellData.borders.top + ' black',
            'border-right': '3px ' + cellData.borders.right + ' black',
            'border-bottom': '3px ' + cellData.borders.bottom + ' black',
            'border-left': '3px ' + cellData.borders.left + ' black',
        });
    }

    $('#cell-edge').click(function(event) {
        var this2 = $(this);
        var width = this2.width();
        var height = this2.height();
        var offsetX = event.pageX - this2.offset().left;
        var offsetY = event.pageY - this2.offset().top;

        // Determine which edge is clicked based on mouse position
        if (offsetX < 10) cellData.borders.left = cellData.borders.left === 'solid' ? 'dashed' : 'solid';
        else if (width - offsetX < 10) cellData.borders.right = cellData.borders.right === 'solid' ? 'dashed' : 'solid';
        else if (offsetY < 10) cellData.borders.top = cellData.borders.top === 'solid' ? 'dashed' : 'solid';
        else if (height - offsetY < 10) cellData.borders.bottom = cellData.borders.bottom === 'solid' ? 'dashed' : 'solid';

        updateCellStyle();
        console.log(cellData);
    });

    $('#setCell').button().on('click', function() {
        $('#cell-dialog').dialog({
            modal: true,
            width: 300,
            height: 250,
            open: function(event, ui) {
                updateCellStyle();
            }
        });
    });

    $('#cancel-button').click(function() {
        console.log("Cancel button pressed");
        $('#cell-dialog').dialog("close");
    });

    $('#confirm-button').click(function() {
        console.log("Confirm button pressed");
        $('#cell-dialog').dialog("close");
    });



// 预加载图片
// var checkedBoxImage = new Image();
// checkedBoxImage.src = 'imgs/checked_box.png';

// var checkBoxImage = new Image();
// checkBoxImage.src = 'imgs/check_box.png';

    // jsonData={};
  // jsonData =my_jsonData; //[原始还原]
   
//show_subTab_manager
//处理分表管理
var data = {
    "tables": [
      {
        "id": 1,
        "name": "A表",
        "rows": [
          {"id": 1, "rowNum": 11},
          {"id": 2, "rowNum": 12},
          {"id": 3, "rowNum": 13}
        ]
      },
      {
        "id": 2,
        "name": "B表",
        "rows": [
          {"id": 1, "rowNum": 14},
          {"id": 2, "rowNum": 15},
          {"id": 3, "rowNum": 16}
        ]
      }
    ]
  };

  var currentOperation = { type: 'add', tableId: null };

  $("#show_subTab_manager").on("click", function() {
    $("#mag_tab_dialog").dialog({
      width: 900,
      modal: true,
      open: function(event, ui) {
        fillTable1();
      }
    });
  });

  $("#mag_tab_add-table").on("click", function() {
    currentOperation = { type: 'add', tableId: null };
    $("#mag_tab_add-subtable-dialog").dialog("option", "title", "增加子表").dialog("open");
    $("#mag_tab_subtableName").val('');
  });

  $("#mag_tab_add-subtable-dialog").dialog({
    autoOpen: false,
    width: 600,
    modal: true
  });

  $("#mag_tab_confirm-add-subtable").on("click", function() {
    var subtableName = $("#mag_tab_subtableName").val().trim();

    if (subtableName) {
      if (currentOperation.type === 'add') {
        var newTableId = new Date().getTime();
        data.tables.push({
          "id": newTableId,
          "name": subtableName,
          "rows": []
        });
        fillTable1();
      } 
      
      if (currentOperation.type === 'edit'){
        var table = data.tables.find(t => t.id === currentOperation.tableId);
        if (table) {
          table.name = subtableName;
        }
        fillTable1();
      }
     





      var inputVal = $("#mag_tab_subtableName").val().trim();
    if (!inputVal) {
        alert("名称不能为空！");
        return;
    }
    if (currentOperation.type === 'addRow') {
        var table = data.tables.find(t => t.id === currentOperation.tableId);
        if (table) {
            var newRowId = new Date().getTime(); // 简单的ID生成策略
            table.rows.push({ "id": newRowId, "rowNum": parseInt(inputVal, 10) });
            fillTable2(table.rows); // 更新table2以显示新增的行
        }
    }

      $("#mag_tab_add-subtable-dialog").dialog("close");
    } else {
      alert("子表名不能为空！");
    }
  });

  function fillTable1() {
    var tbody = $("#mag_tab_table1 tbody");
    tbody.empty();
    $.each(data.tables, function(i, table) {
        var seqNum = i + 1;
        var deleteButton = $('<button>').text('删除').on('click', function(e) {
            e.stopPropagation(); // 防止点击删除按钮时触发行点击事件
            data.tables = data.tables.filter(t => t.id !== table.id);
            fillTable1();
            $("#mag_tab_table2 tbody").empty(); // 清除table2的内容
        });
        var editButton = $('<button>').text('修改').on('click', function(e) {
            e.stopPropagation(); // 防止点击修改按钮时触发行点击事件
            currentOperation = { type: 'edit', tableId: table.id };
            $("#mag_tab_add-subtable-dialog label").text("子表名称："); // 修改标签文本
            $("#mag_tab_subtableName").val(table.name);
            $("#mag_tab_add-subtable-dialog").dialog("option", "title", "修改子表名").dialog("open");
        });

        var addRowButton = $('<button>').text('增加行').on('click', function(e) {
        e.stopPropagation(); // 防止触发行点击事件
        currentOperation = { type: 'addRow', tableId: table.id };
        $("#mag_tab_subtableName").val(''); // 清空输入值
        $("#mag_tab_add-subtable-dialog").dialog("option", "title", "增加行"); // 修改对话框标题
        $("#mag_tab_add-subtable-dialog label").text("行号："); // 修改标签文本
        $("#mag_tab_add-subtable-dialog").dialog("open"); // 打开对话框
        });
        // 创建表格行
        var tr = $("<tr>")
            .append(
                $("<td>").text(seqNum),
                $("<td>").text(table.name),
                $("<td>").append(deleteButton),
                $("<td>").append(editButton),
                $("<td>").append(addRowButton)
            )
            .on('click', function() { // 为行添加点击事件
                $("#mag_tab_table1 tr").removeClass("mag_tab_highlighted");
                $(this).addClass("mag_tab_highlighted");
                fillTable2(table.rows); // 根据点击的行填充table2
            });

        tbody.append(tr);
    });
}
function fillTable2(rows) {
    var tbody = $("#mag_tab_table2 tbody");
    tbody.empty();
    $.each(rows, function(i, row) {
        var seqNum = i + 1; // 序号从1开始

        var deleteButton = $('<button>').text('删除').on('click', function(e) {
            e.stopPropagation(); // 阻止事件冒泡到行点击事件

            // 从当前分表中删除选中的行
            var currentTableRows = data.tables.find(table => table.rows.some(r => r.id === row.id)).rows;
            var rowIndex = currentTableRows.findIndex(r => r.id === row.id);
            if (rowIndex > -1) {
                currentTableRows.splice(rowIndex, 1);
            }

            fillTable2(currentTableRows); // 重新填充table2来显示更新后的数据
        });

        var tr = $("<tr>")
            .append($("<td>").text(seqNum), $("<td>").text(row.rowNum), $("<td>").append(deleteButton))
            .on('click', function() {
                // 在点击时添加或移除高亮效果
                $("#mag_tab_table2 tr").removeClass("mag_tab_highlighted"); // 先移除其他行的高亮
                $(this).addClass("mag_tab_highlighted"); // 为点击的行添加高亮
            });

        tbody.append(tr);
    });
}

//处理分表管理完成 

 // 切换一级菜单显示
 $('#Main_File_fileButton').on('click', function(event){
        $('#Main_File_fileMenu').toggle();
        event.stopPropagation();
    });

    // 二级菜单显示
    $('#Main_File_fileMenu > li').has('ul').hover(function(){
       $(this).children('.Main_File_submenu').stop(true, true).fadeIn(100);
    }, function(){
        $(this).children('.Main_File_submenu').stop(true, true).fadeOut(100);
    });

    // 点击其他地方关闭所有菜单
    $(document).on('click', function(){
        $('#Main_File_fileMenu').hide();
        $('.Main_File_submenu').hide();
    });

    // 防止菜单内部点击时菜单关闭
    $('#Main_File_fileMenu').on('click', function(event){
        event.stopPropagation();
    });
    


    $('#myCanvas').click(function(e) {
      const rect = this.getBoundingClientRect();
      var x = e.clientX - rect.left - window.scrollX; // 考虑水平滚动
      var y = e.clientY - rect.top - window.scrollY; // 考虑垂直滚动

      var cursorX = event.pageX;
      var cursorY = event.pageY;
      x=cursorX;
      y=cursorY;

    
      var canvasOffset = $('#myCanvas').offset(); 


      cellStartX = canvasOffset.left+tableOffsetX;
      cellStartY = canvasOffset.top+tableOffsetY;

      var m_cell_x=0;
      var m_cell_y=0;
      var m_cell_w=0;
      var m_cell_h=0;

    //计算被合并的单元格的起始位置
    if(cell.parentCol>=0||cell.parentRow>=0)
    {
     
      m_cell_x=jsonData[cell.parentRow].cells[cell.parentCol].x;
      m_cell_y=jsonData[cell.parentRow].cells[cell.parentCol].x;

      m_cell_w=jsonData[cell.parentRow].cells[cell.parentCol].mWidth;
      m_cell_h=jsonData[cell.parentRow].cells[cell.parentCol].mHeight;
    }
    

    //console.log("mouseX:" ,x,"mouseY:", y,"cellStart_x:",cellStartX,"cellStart_Y:",cellStartY);
    let temp_rows=0;
    let temp_columns=0;
    jsonData.forEach(row => {
     
      row.cells.forEach(cell => {

          var cell_X = cellStartX + cell.x;
          var cell_Y = cellStartY + cell.y;  

        //console.log("cellX:" ,cell_X,"cellY:" ,cell_Y);
    if (x > cell_X && x < cell_X + cell.width && y > cell_Y && y < cell_Y + cell.height) 
    {
          
            //let input = $('#text-input');
        
            //console.log(cell.x+" <-x y-> "+ cell.y)
            //input.val(cell.content);
            //console.log("Q7 :------------"+cell.content);
          
            //console.log(cell.content+" cell.y="+cell.y);
      
          
            editor_locked_cellRecord.columns=temp_columns;
            editor_locked_cellRecord.rows=temp_rows;
            //console.log("Q2:  editor_locked_cellRecord.rows",editor_locked_cellRecord.rows," columns:",editor_locked_cellRecord.columns)

            textData=cell;
            lastTextData=cell;
            lastTextData.text=cell.content;

            if(allowEditCell||1==1)
            {
            


              

              // 如果你之后需要让下层canvas重新接收事件
              document.getElementById('main_canvas').style.pointerEvents='none';
              document.getElementById(lastPageName).style.pointerEvents='none';
              document.getElementById('page-1-content_div').style.pointerEvents='none';

              

              document.getElementById('myCanvas').style.pointerEvents = 'none';
              // 如果你之后需要让下层canvas重新接收事件
              document.getElementById('cellsCanvas').style.pointerEvents = 'auto';
            }

           // console.log(" pointerEvents  off ------------44------------------->");
            var checkBoxX=0;
            var checkBoxY=0;

            if (cell.hasCheckBox) {
          
            // 请根据你的图片实际大小调整这里的偏移和位置
            checkBoxX =  45; // 举例，复选框距单元格左边界10像素           
          
            }

            loadAtFirstTime=false;
          // console.log(" Q9999999999999999999999----------------->");
          if(cell.rowspan>0||cell.colspan>0)
          {
           
               myCellCanvas = document.getElementById('cellsCanvas');
             
              if (myCellCanvas) {
           
              myCellCanvas.style.left=(cell_X+checkBoxX)+"px";
              myCellCanvas.style.top =(cell_Y+checkBoxY)+"px";
              myCellCanvas.width=cell.mWidth-checkBoxX;
              myCellCanvas.height=cell.mHeight;
  
            
              lastSizeOfCellCanvas.left=(cell_X+checkBoxX)+"px";
              lastSizeOfCellCanvas.top=(cell_Y+checkBoxY)+"px";
                   
              lastSizeOfCellCanvas.width=cell.mWidth-checkBoxX;
              lastSizeOfCellCanvas.height=cell.mHeight;

              document.getElementById('main_canvas').style.pointerEvents='none';
              document.getElementById(lastPageName).style.pointerEvents='none';
  
              document.getElementById('myCanvas').style.pointerEvents = 'none';
              // 如果你之后需要让下层canvas重新接收事件
              document.getElementById('cellsCanvas').style.pointerEvents = 'auto';
              editor_locked_cellRecord.columns=temp_columns;
              editor_locked_cellRecord.rows=temp_rows;
  
              //console.log("Q2:  editor_locked_cellRecord.rows",editor_locked_cellRecord.rows," columns:",editor_locked_cellRecord.columns)
              lastTextData=cell;
              compressStyles();                
              generateLinesData();       
              where_to_call=" 底层光标事件驱动 "+whereCallDrawTable;    
              renderText();
  
              }


          }
          else
          {
            // input.css({
            //         display: 'block',
            //         left: cell_X+checkBoxX,
            //         top: cell_Y ,
            //         width: cell.width-checkBoxX,
            //         height: cell.height
            //      }).focus();
            let   myCellCanvas = document.getElementById('cellsCanvas');
            var   canvasOffset = $('#myCanvas').offset(); 
           
           
						

           // console.log(" pointerEvents  off ------------------------------->");
            let cellStartX = canvasOffset.left+tableOffsetX;
            let cellStartY = canvasOffset.top+tableOffsetY;

             //处理被合并的单元格，被合并后没有
          if(cell.parentCol>=0&&cell.parentRow>=0)
          {
            //console.log("Q2 :------------002处理被合并的单元格，被合并后没有"+cell.content);
            jsonData[cell.parentRow].cells[cell.parentCol].selected=true;
            clickInTableEare=true;

          
              
            if (myCellCanvas) {
            //console.log("Q2 :------------myCellCanvas"+cell.content);

            myCellCanvas.style.left=(m_cell_x+checkBoxX)+"px";
            myCellCanvas.style.top =(m_cell_y+checkBoxY)+"px";
            myCellCanvas.width=m_cell_w;
            myCellCanvas.height=m_cell_h;

          
            lastSizeOfCellCanvas.left=(m_cell_x)+"px";
            lastSizeOfCellCanvas.top=(m_cell_y)+"px";
                  
            lastSizeOfCellCanvas.width=m_cell_w;
            lastSizeOfCellCanvas.height=m_cell_h;
            

            lastTextData= jsonData[cell.parentRow].cells[cell.parentCol];
            lastTextData.text= jsonData[cell.parentRow].cells[cell.parentCol].content;
            jsonData[temp_rows].cells[temp_columns].selected=false;

            editor_locked_cellRecord.columns=cell.parentCol;
            editor_locked_cellRecord.rows=cell.parentRow;
            //console.log("Q2:  editor_locked_cellRecord.rows",editor_locked_cellRecord.rows," columns:",editor_locked_cellRecord.columns)

           // console.log("Q2 :------------lastTextData.text:"+lastTextData.text);
            compressStyles();                
            generateLinesData();           
            renderText();
            }
            
          }
          else
          {

            lastTextData=cell;
            lastTextData.text=cell.content;
            compressStyles();                
            generateLinesData();   
            where_to_call="drawTable 01 cell.showBorder==true"+ " 原始调用:"+whereCallDrawTable;        
            renderText();
            if (myCellCanvas) {

                 // console.log(myCellCanvas); // 这应该显示具体的canvas元素信息，而不是null或undefined            
                  myCellCanvas.style.left=(cell_X+checkBoxX)+"px";
                  myCellCanvas.style.top =(cell_Y+checkBoxY)+"px";
                  myCellCanvas.width=cell.width-checkBoxX;
                  myCellCanvas.height=cell.height;             
           
                  lastSizeOfCellCanvas.left=(cell_X+checkBoxX)+"px";
                  lastSizeOfCellCanvas.top=(cell_Y+checkBoxY)+"px";
                  lastSizeOfCellCanvas.width=cell.width-checkBoxX;
      
                  lastSizeOfCellCanvas.height= cell.height;
                 // console.log("lastSizeOfCellCanvas:left:"+lastSizeOfCellCanvas.left," top:"+lastSizeOfCellCanvas.top," lastSizeOfCellCanvas.width:"+lastSizeOfCellCanvas.width," lastSizeOfCellCanvas.height:"+lastSizeOfCellCanvas.height	);
            }  
            
          }

    
          
          
           
                const cell2 = getCellByCoords(selectionStartX, selectionStartY);

                let tempCellInfo=[];//
                if(cell2!=null)
                 tempCellInfo={x:cell2.x,y:cell2.y};

                let selectCellCounters=0;
               

                //处理点击后，是否对这个单元格进行处理。
                for(var n=0;n<jsonData.length;n++)
                {
                  let tempSells=jsonData[n];
                  for(var m=0;m<tempSells.cells.length;m++)
                  {
                   
                    if(tempSells.cells[m].selected==true)
                    selectCellCounters++;
                    //console.log(" jsonData["+n+"]["+m+"]:",tempSells.cells[m].selected);

                  }
                  
                }		

                // if(cell2!=null)
                // {             

                
                //   if(latestSelectCells.x!==tempCellInfo.x||latestSelectCells.y!=tempCellInfo.y)
                //   {                
                  
                //     cell2.selected==true;
                //     console.log("=======================>. didn't same;"," latestSelectCells:",latestSelectCells," tempCellInfo:",tempCellInfo," selectedCell.length:",selectedCells.length," selectCellCounters:",selectCellCounters);
                //     latestSelectCells=tempCellInfo;
                //   }
                //   else
                //   {
                  
                //     if(selectCellCounters<=1)
                //     cell2.selected=!cell2.selected;        
                    
                  
                //    // redraw();
                //     console.log("=======================>. same;"," latestSelectCells:",latestSelectCells," tempCellInfo:",tempCellInfo," selectCellCounters",selectCellCounters);
                    
                //   }              
                // }

                // 当你想让上层canvas接收事件，下层canvas不接收事件
                if(allowEditCell)
                {
                    document.getElementById('myCanvas').style.pointerEvents = 'none';
                    // 当你想让上层canvas接收事件，下层canvas不接收事件
                    document.getElementById('myCanvas').style.pointerEvents = 'none';
                    // 如果你之后需要让下层canvas重新接收事件
                    document.getElementById('main_canvas').style.pointerEvents='none';
                    document.getElementById(lastPageName).style.pointerEvents='none';
                  // 如果你之后需要让下层canvas重新接收事件
                  document.getElementById('cellsCanvas').style.pointerEvents = 'auto';
                  document.getElementById('cellsCanvas').style.cursor = 'crosshair';
                }
          }
     
                if (cell.hasCheckBox) {
                              
                              cell.checkStatus = !cell.checkStatus; // 切换复选框状态
                            ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
                          
                }

                 //drawTable(jsonData);
          
          //   input.off('blur').on('blur', function() {
          //   cell.content = this.value;
          //   input.hide();
          //   //drawTable(jsonData);
          // });
        }
        temp_columns++;
      });
      temp_rows++;
      temp_columns=0;
    });

    whereCallDrawTable=" 选择表格操作重绘";
    redraw();
  });



    $(".menu").click(function(){
        
        // 移除所有菜单项的.active类
          $(".menu").removeClass("active");
        // 为当前被点击的菜单项添加.active类
        $(this).addClass("active");

        
        console.log("your click:"+$(this).attr("data-target"));

        var clickMenuId=$(this).attr("data-target");

        var targetSelector = "#" + $(this).attr("data-target");
        
        var targetId = $(this).attr("data-target"); // 获取ID或类的名称
        $(".submenu2").hide(); // 隐藏所有子菜单
        $(".submenu").hide(); // 隐藏所有子菜单
        if(clickMenuId=="Files")
        {
          console.log("hello girl");
          return;
        }

        if(clickMenuId=="start")
        {        
         
          $("#" + targetId).toggle(); // 直接使用ID选择器
          $(".submenu-container").show();
          
         // $('.submenu div').attr('style', 'display: block;');
        }        
        else 
        {
         
          $("#" + targetId).toggle(); // 直接使用ID选择器
          $(".submenu-container").show();
        }
        
       

        
    	




    });


        // 默认显示“开始”菜单的二级菜单，同时为其添加.active类高亮显示
    var startMenu = $("#start");
    startMenu.show();
    $(".submenu-container").show(); // 确保容器是可见的	
	  $("[data-target='start']").addClass("active"); // 高亮“开始”菜单项


 function saveState() {
     // 这里使用深复制来保存当前状态
     historyStack.push(JSON.parse(JSON.stringify(jsonData)));
     redoStack = []; // Clear the redo stack after a new action
 }
 
 function undo() {
     if (historyStack.length > 0) {
         redoStack.push(JSON.parse(JSON.stringify(jsonData)));
         jsonData = historyStack.pop();
         whereCallDrawTable=" undo重绘:01";
         redraw()
		 console.log("-=========undo()===========");
     }
 }
 
 function redo() {
     if (redoStack.length > 0) {
         historyStack.push(JSON.parse(JSON.stringify(jsonData)));
         jsonData = redoStack.pop();
         whereCallDrawTable=" Redo重绘:01";
         redraw()
		 console.log("-=========redo()===========");
     }
 }
function addRow()
{

// 步骤1&2: 选择并复制jsonData中最后一个cells元素组
var newCellsGroup = JSON.parse(JSON.stringify(jsonData[jsonData.length - 1].cells));

// 步骤3: （可选）修改新复制的cells元素组的属性，比如根据需要调整x或y属性
var lastCellY=0;
//获取表格的总高度，作为最后一行表格的y坐标
jsonData.forEach(function(row) {
    // 找到每行的最后一个单元格
    var lastCell = row.cells[row.cells.length - 1];
    lastCellY=lastCell.y+lastCell.height;

});

newCellsGroup.forEach(function(cell) {
    cell.y = lastCellY; // 假设每个cell的高度为40，这里我们简单地将y增加40以移动到新的行
    cell.showBorder=true;
});

// 步骤4: 将复制并可能已修改的cells元素组添加到jsonData数组的末尾
jsonData.push({cells: newCellsGroup});
//updateForSellMerging()
  saveState();
    
  whereCallDrawTable=" 表格新增行";//在哪调用了drawTable
        drawTable();

  console.log("-=========add row()===========");
}

function addCol()
{

// 遍历jsonData中的每个元素（每行）
jsonData.forEach(function(row) {
    // 找到每行的最后一个单元格
    var lastCell = row.cells[row.cells.length - 1];
    
    // 复制最后一个单元格（深复制）
    var newCell = JSON.parse(JSON.stringify(lastCell));
    
    // 调整复制单元格的x值，使其位于行的最右侧
    // 新的x值是当前最后一个单元格的x值加上其宽度
    newCell.x = lastCell.x + lastCell.width;
    newCell.showBorder=true;
    
    // 将调整后的单元格添加到当前行
    row.cells.push(newCell);
  

});
  updateForSellMerging()
 
  saveState();
  whereCallDrawTable=" 初始表";//在哪调用了drawTable
     //   drawTable();

  console.log("-=========add row()===========");
}
$("#MergeCells").click(doSellMerging);
$("#splitCells").click(doSellSplit);
 $("#undo").click(undo);
 $("#redo").click(redo);
 $("#addRow").click(addRow);
 $("#addCol").click(addCol);

 function doSellSplit()
 {

  highlightButton('splitCells', 0);
  highlightButton('MergeCells', 0);
      
  console.log('表格选择鼠标左键被释放。');
        var canvas = $('#myCanvas');
     		var context = canvas.get(0).getContext('2d');
     		var rect = canvas.get(0).getBoundingClientRect();
     		var canvasOffset = canvas.offset();
	    

        //查询是否有需要合并的单元格,如果有就弹出菜单
         var hasMoreThanOneCellSelected = 0;
         var selectedRow=0;
         var selectedCol=0;

         jsonData.forEach(function(rowData, rowIndex) {
         rowData.cells.forEach(function(cell, cellIndex) {           
             if( cell.selected ==true)
             {
              selectedRow=rowIndex;
              selectedCol=cellIndex;

              hasMoreThanOneCellSelected++;
              
              console.log("selecteded cell row:"+rowIndex+" index = " + cellIndex +" rowSpan = " + 

              cell.rowspan+" cell col Span = " + cell.colspan+" cellwidth="+cell.width+

              " cellheight="+cell.height+" cell.mwidth ="+cell.mWidth+ "cell.mHeidht="+cell.mHeight);
       
                 var tempRowspan=cell.rowspan
                for( var j=rowIndex;j<=(rowIndex+tempRowspan);j++ )//处理单列，一行一行的处理
                {
                  //拆分列时，每列的高度要重新计算，与相邻的单元格高度一致
                  var tempCellHeight=0;
                  if(cellIndex>0)
                  {
                    tempCellHeight=jsonData[j].cells[cellIndex-1].height; //同一行前一列的高
                  }
                  var offsetY=0;
                  for(var yy=0;yy<rowIndex;yy++)
                  {
                    offsetY+=jsonData[yy].cells[cellIndex].height;
                  }
                  var netxCellRow=rowIndex+tempRowspan;
                
                  console.log("单列处理----》处理单列j:"+j+"  rowIndex:"+rowIndex+" rowIndex+cell.rowspan:"+netxCellRow+" cellIndex:"+cellIndex+" cell rowspan = " + tempRowspan);
                  jsonData[j].cells[cellIndex].showBorder = true;
                  jsonData[j].cells[cellIndex].parentRow=-1;
                  jsonData[j].cells[cellIndex].parentCol=-1;
                  jsonData[j].cells[cellIndex].rowspan=0;
                  jsonData[j].cells[cellIndex].colspan=0;
                  
                  jsonData[j].cells[cellIndex].height=tempCellHeight
                  jsonData[j].cells[cellIndex].mHeight=tempCellHeight;
                  jsonData[j].cells[cellIndex].y=offsetY;
                }

                var tempColspan=cell.colspan
                for( var i=cellIndex;i<=cellIndex+tempColspan;i++)//处理单行，一列一列的处理
                {
                  console.log(" 处理行单行:"+cellIndex+"处理列："+i);
                  jsonData[selectedRow].cells[i].showBorder = true;
                  jsonData[selectedRow].cells[i].parentCol=-1;
                  jsonData[selectedRow].cells[i].parentRow=-1;
                  jsonData[selectedRow].cells[i].rowspan=0;
                  jsonData[selectedRow].cells[i].colspan=0;

                }

                for( var i=rowIndex;i<=rowIndex+tempRowspan;i++)
                {
             

                for( var j=cellIndex;j<=cellIndex+tempColspan;j++ )
                  {
                    console.log("处理行："+i+"处理列:"+j)+" showBorder:";
                    jsonData[i].cells[j].showBorder = true;
                    jsonData[i].cells[j].parentRow=-1;
                    jsonData[i].cells[j].parentCol=-1;
                    jsonData[i].cells[j].selected=true;
                    jsonData[i].cells[j].rowspan=0;
                    jsonData[i].cells[j].colspan=0;
                  }
                }  

             }

           
            
        });
      });
      jsonData[selectedRow].cells[selectedCol].rowspan = 0;
      jsonData[selectedRow].cells[selectedCol].colspan = 0;

      updateForSellMerging();
      saveState();
	 
      whereCallDrawTable=" 拆分单元格后重绘:01";
     redraw();
      return;

        //查询是否有需要合并的单元格,如果有就弹出菜单
        // if(hasMoreThanOneCellSelected>1)
        //  drawMenu(x, y);

        console.log('合并单元格 数量：'+hasMoreThanOneCellSelected);
         

         // Merge selected cells
         const selectedCells = [];
         const mergedCells = []; //记录要合并的单元行号与列号
    
       
           jsonData.forEach(function(rowData, rowIndex) 
           {
              let n=0;
       
               rowData.cells.forEach(function(cell) 
               { 
                   if (cell.selected) 
                  {
                    cell.row=0;
                    cell.col=0;

            
                   selectedCells.push(cell);//
                   mergedCells.push(cell); 
                   console.log("-=========selectedCells======将已选的单元格汇总 ====rowIndex:====第 "+String(rowIndex)+" 行 第:"+String(n)+"列 content:"+cell.content);
                  }
                   n++;
               });

               console.log("----------");
              
         });
   
         
   
   
       if(selectedCells.length > 1) {
  
       const minX = Math.min(...selectedCells.map(cell => cell.x));
       const minY = Math.min(...selectedCells.map(cell => cell.y));
       const maxX = Math.max(...selectedCells.map(cell => cell.x + cell.width));
       const maxY = Math.max(...selectedCells.map(cell => cell.y + cell.height));
       let mergedContent = "";

    
       console.log("要合并的后的单元格起点 X： "+String(minX)+ "  Y:"+String(minY));
       console.log("要合并的后的单元格终点 X： "+String(maxX)+ "  Y:"+String(maxY));


       const startCell = getCellByCoords(minX+2, minY+2);
       const startCellIndex=getCRFormCell(minX+2,minY+5,"计算跨行数取开始：");

      const endCellIndex=getCRFormCell(maxX-5,maxY-5,"计算跨行数取最大：");


       console.log("合并单元格 startCellIndex :"+startCellIndex.row +" <=>  "+startCellIndex.col);

       selectedCells.forEach(cell => {
         mergedContent = " "; // Concatenate the content of selected cells
         cell.showBorder = true;
     
         console.log("要合并的=第 "+String(cell.content));
         cell.content = ""; // Clear the content of the cell after merging
       });
   
   

       var cellRowSpan=0;
       var cellColSpan=0;
  


      cellRowSpan=endCellIndex.row-startCellIndex.row+1;
      cellColSpan=endCellIndex.col-startCellIndex.col+1;


       			//将被合并的单元格作合并
       			mergedCells.forEach(cell=>{

								//console.log("-=========mergedCells===第 "+String(cell.row)+" 行 第:"+String(cell.col)+"列 content:"+cell.content+" startCellIndex.row="+String(startCellIndex.row)+" endCellIndex.col="+String(startCellIndex.col));
                if(startCellIndex.row == cell.row && startCellIndex.col == cell.col)
                {
                  //给父亲单元格记录跨行 跨列的数值
                  jsonData[cell.row].cells[cell.col].parentRow=-1;
                  jsonData[cell.row].cells[cell.col].parentCol=-1;
                  jsonData[cell.row].cells[cell.col].rowspan=0;
                  jsonData[cell.row].cells[cell.col].colspan=0;

                 // console.log("-=首行-----------------=");

                }
                else
                {
                  //给被合并的单元格，，记录父亲行列号，，
                  jsonData[cell.row].cells[cell.col].parentRow=-1;
                  jsonData[cell.row].cells[cell.col].parentCol=-1;
                  //console.log("-=非首行-----------------=");
                }
        
						}     
						)

       if (startCell) {
         startCell.mWidth  = maxX - minX;
         startCell.mHeight = maxY - minY;
         startCell.showBorder = true;
         startCell.rowspan=0;
         startCell.colspan=0;
         startCell.content = mergedContent.trim(); // Update the content of the start cell
         console.log("要合并的后的单元格 "+String(cell.content)+ "  X:"+String(minX)+ "  Y:"+String(minY)+" w:"+String(startCell.width)+" h:"+String(startCell.height)+" mWidth:"+String(startCell.mWidth)+" mHeight:"+String(startCell.mHeight));
         jsonData[startCellIndex.row].cells[startCellIndex.col].rowspan=0;
         jsonData[startCellIndex.row].cells[startCellIndex.col].colspan=0;
         updateCellSize(startCellIndex.row,startCellIndex.col,minX,minY,startCell.Width,startCell.Height);
       }
     }
   

     //从jsonData从最小的x开始遍历,找到最大的结束位
     var cellRowSpans=0; //单元格横跨单元格个数
    

   
     jsonData.forEach(function(rowData, rowIndex) 
           {
              let n=0;
       
               rowData.cells.forEach(function(cell) 
               {        
                  
                   console.log("合并后观察====rowIndex:====第 "+String(rowIndex)+" 行 第:"+String(n)+"列  x: "+cell.x+"  y: "+cell.y+"  w: "+cell.width+"  h: "+cell.height+" parentRowIndex: "+cell.parentRow+"  parentColIndex: "+cell.parentCol," rowspan: "+cell.rowspan+" colspan: "+cell.colspan+" mWidth:"+String(cell.mWidth)+" mHeight:"+String(cell.mHeight)+" show:"+cell.showBorder);
                 
                   n++;
               });

               console.log("----------");
              
         });
   
     saveState();
	  console.log("===要合并的后的单元格saveState();")
     redraw();
     return;
     ///////////////////////合并完成

 }
 
 function doSellMerging()
 {

   

      highlightButton('MergeCells', 0);
      highlightButton('splitCells', 0);
        console.log('表格选择鼠标左键被释放。');
        var canvas = $('#myCanvas');
     		var context = canvas.get(0).getContext('2d');
     		var rect = canvas.get(0).getBoundingClientRect();
     		canvasOffset = canvas.offset();
	    

        //查询是否有需要合并的单元格,如果有就弹出菜单
         var hasMoreThanOneCellSelected = 0;
         jsonData.forEach(function(rowData, rowIndex) {
         rowData.cells.forEach(function(cell, cellIndex) {           
             if( cell.selected ==true)
             hasMoreThanOneCellSelected++;
        });
      });
       

        //查询是否有需要合并的单元格,如果有就弹出菜单
        // if(hasMoreThanOneCellSelected>1)
        //  drawMenu(x, y);

        console.log('合并单元格 数量：'+hasMoreThanOneCellSelected);
         

         // Merge selected cells
         const selectedCells = [];
         const mergedCells = []; //记录要合并的单元行号与列号
    
       
           jsonData.forEach(function(rowData, rowIndex) 
           {
              let n=0;
       
               rowData.cells.forEach(function(cell) 
               { 
                   if (cell.selected) 
                  {
                    cell.row=rowIndex;
                    cell.col=n;

            
                   selectedCells.push(cell);//
                   mergedCells.push(cell); 
                   console.log("-=========selectedCells======将已选的单元格汇总 ====rowIndex:====第 "+String(rowIndex)+" 行 第:"+String(n)+"列 content:"+cell.content);
                  }
                   n++;
               });

               console.log("----------");
              
         });
   
         
   
   
       if(selectedCells.length > 1) {
  
       const minX = Math.min(...selectedCells.map(cell => cell.x));
       const minY = Math.min(...selectedCells.map(cell => cell.y));
       const maxX = Math.max(...selectedCells.map(cell => cell.x + cell.width));
       const maxY = Math.max(...selectedCells.map(cell => cell.y + cell.height));
       let mergedContent = "";

    
       console.log("要合并的后的单元格起点 X： "+String(minX)+ "  Y:"+String(minY));
       console.log("要合并的后的单元格终点 X： "+String(maxX)+ "  Y:"+String(maxY));


       const startCell = getCellByCoords(minX+2, minY+2);
       const startCellIndex=getCRFormCell(minX+2,minY+5,"计算跨行数取开始：");

      const endCellIndex=getCRFormCell(maxX-5,maxY-5,"计算跨行数取最大：");


       console.log("合并单元格 startCellIndex :"+startCellIndex.row +" <=>  "+startCellIndex.col);

       selectedCells.forEach(cell => {
         mergedContent += cell.content + " "; // Concatenate the content of selected cells
         cell.showBorder = false;
        //  cell.width = 0;
        //  cell.height = 0;
         console.log("要合并的=第 "+String(cell.content));
         cell.content = ""; // Clear the content of the cell after merging
       });
   
   

       var cellRowSpan=0;
       var cellColSpan=0;
  
      // console.log("合并单元格开始行号:"+startCellIndex.row+"  列号:"+String(startCellIndex.col));
      // console.log("合并单元格 结束行号:"+endCellIndex.row);
      // console.log("合并单元格 结束列号:"+endCellIndex.col);

      cellRowSpan=endCellIndex.row-startCellIndex.row+1;
      cellColSpan=endCellIndex.col-startCellIndex.col+1;
      // console.log("合并单元格 跨行数 rowspan："+cellRowSpan);
      // console.log("合并单元格 跨列数 colspan："+cellColSpan);

       			//将被合并的单元格作合并
       			mergedCells.forEach(cell=>{

								//console.log("-=========mergedCells===第 "+String(cell.row)+" 行 第:"+String(cell.col)+"列 content:"+cell.content+" startCellIndex.row="+String(startCellIndex.row)+" endCellIndex.col="+String(startCellIndex.col));
                if(startCellIndex.row == cell.row && startCellIndex.col == cell.col)
                {
                  //给父亲单元格记录跨行 跨列的数值
                  jsonData[cell.row].cells[cell.col].parentRow=-1;
                  jsonData[cell.row].cells[cell.col].parentCol=-1;
                  jsonData[cell.row].cells[cell.col].rowspan=cellRowSpan;
                  jsonData[cell.row].cells[cell.col].colspan=cellColSpan;

                 // console.log("-=首行-----------------=");

                }
                else
                {
                  //给被合并的单元格，，记录父亲行列号，，
                  jsonData[cell.row].cells[cell.col].parentRow=startCellIndex.row;
                  jsonData[cell.row].cells[cell.col].parentCol=startCellIndex.col;
                  //console.log("-=非首行-----------------=");
                }
        
						}     
						)

       if (startCell) {
         startCell.mWidth  = maxX - minX;
         startCell.mHeight = maxY - minY;
         startCell.showBorder = true;
         startCell.rowspan=endCellIndex.row-startCellIndex.row;
         startCell.colspan=endCellIndex.col-startCellIndex.col;
         startCell.content = mergedContent.trim(); // Update the content of the start cell
         console.log("要合并的后的单元格 "+String(cell.content)+ "  X:"+String(minX)+ "  Y:"+String(minY)+" w:"+String(startCell.width)+" h:"+String(startCell.height)+" mWidth:"+String(startCell.mWidth)+" mHeight:"+String(startCell.mHeight));
         jsonData[startCellIndex.row].cells[startCellIndex.col].rowspan=endCellIndex.row-startCellIndex.row;
         jsonData[startCellIndex.row].cells[startCellIndex.col].colspan=endCellIndex.col-startCellIndex.col;
         updateCellSize(startCellIndex.row,startCellIndex.col,minX,minY,startCell.mWidth,startCell.mHeight);
       }
     }
   

     //从jsonData从最小的x开始遍历,找到最大的结束位
     var cellRowSpans=0; //单元格横跨单元格个数
    

   
     jsonData.forEach(function(rowData, rowIndex) 
           {
              let n=0;
       
               rowData.cells.forEach(function(cell) 
               {        
                  
                   console.log("合并后观察====rowIndex:====第 "+String(rowIndex)+" 行 第:"+String(n)+"列  x: "+cell.x+"  y: "+cell.y+"  w: "+cell.width+"  h: "+cell.height+" parentRowIndex: "+cell.parentRow+"  parentColIndex: "+cell.parentCol," rowspan: "+cell.rowspan+" colspan: "+cell.colspan+" mWidth:"+String(cell.mWidth)+" mHeight:"+String(cell.mHeight)+" show:"+cell.showBorder);
                 
                   n++;
               });

               console.log("----------");
              
         });
   
     saveState();
	  console.log("===要合并的后的单元格saveState();")
    whereCallDrawTable=" 要合并的后的单元格!";
     redraw();
     return;
     ///////////////////////合并完成
 }
    $(document).on("contextmenu", function(e) {
    e.preventDefault(); // 阻止默认的右键菜单弹出
    });


$(menuCanvas).on('click', function(e) {
  const rect = menuCanvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;

  if (y > 30 && y < 50) 
  {
          console.log('合并单元格 clicked');
         

      // Merge selected cells
      const selectedCells = [];
 
  			jsonData.forEach(function(rowData, rowIndex) 
        {
    		    rowData.cells.forEach(function(cell) 
            {
     			     if (cell.selected) 
               {
        				selectedCells.push(cell);
                console.log("-=========selectedCells======将已选的单元格汇总===========");
                // 如果单元格有复选框，则切换选中状态
             
      		     }
 
            });
      });

  


    if(selectedCells.length > 1) {
    const minX = Math.min(...selectedCells.map(cell => cell.x));
    const minY = Math.min(...selectedCells.map(cell => cell.y));
    const maxX = Math.max(...selectedCells.map(cell => cell.x + cell.width));
    const maxY = Math.max(...selectedCells.map(cell => cell.y + cell.height));
    let mergedContent = "";
    selectedCells.forEach(cell => {
      mergedContent += cell.content + " "; // Concatenate the content of selected cells
      cell.showBorder = false;
      cell.width = 0;
      cell.height = 0;
      cell.content = ""; // Clear the content of the cell after merging
    });

    
    const startCell = getCellByCoords(minX, minY);
    if (startCell) {
      startCell.width = maxX - minX;
      startCell.height = maxY - minY;
      startCell.showBorder = true;
      startCell.content = mergedContent.trim(); // Update the content of the start cell
      
      updateCellSize(minX, minY,startCell.width, startCell.height);
    }

    
  }

  whereCallDrawTable=" 从菜单操作表格重绘01!";

  redraw();

  isIntoMenuSelection=0;//进入菜单选择状态
  } else if (y > 60 && y < 80) {
    console.log('取消 clicked');
    isIntoMenuSelection=0;//进入菜单选择状态
  }

  $(menuCanvas).hide();
});

// Initial hide of the menu canvas
	hideMenu();
  function drawCoordinates(x, y) {
  // Clear the canvas
  ctx1.clearRect(0, canvas1.height-12, canvas1.width, canvas1.height);
  
  // Optionally redraw other stuff here, e.g., a grid
  
  // Draw the coordinates
  ctx1.font = '14px Arial';
  ctx1.fillStyle = '#808080'; // Light blue color
  ctx1.fillText(x + '行 * ' +y+ '列 表格', 10, canvas1.height - 10);
}




          // Mousemove event to highlight squares
  $('#canvasPopup').mousemove(function(e) 
  {
    var rect = canvas1.getBoundingClientRect();
    var x = e.clientX - rect.left;
    var y = e.clientY - rect.top;
    console.log('正在执行  表格 插入操作'); 
    drawGrid(); // Redraw the grid to clear previous highlights
    highlightSquares(x, y); // Highlight squares based on mouse position

   
    var selected = highlightSquares(x, y);
    // tableRows=selected.columns;
    // tableLines=selected.rows;
    drawCoordinates(selected.rows, selected.columns);

  });

    var canvas = $('#myCanvas')[0];
    var ctx = canvas.getContext('2d');
    var curOnBorder=0; //光标在边框上
    var curOnBorderAndButtonDown=0; //光标在边框上且左键按钮被按下  
    var leftButtonDown=0; //左键按钮被按下
    var onBottomLine=0;   //光标在表格底部边框上

    var isMoveTable=0;    //是否在移动表格 1=是 0=否
    var isOnMoveTable=0;  //是否在移动表格的边框上 1=是 0=否

      // 定义自定义光标样式
    var myCursor = "url('imgs/down_cursor.png'), auto";




  function renderPosition(x, y,showText) {
    // Clear a rectangle area for the coordinates to avoid overlap
    ctx.clearRect(20, 0, 550, 16); // Clear a small area at the top-left corner
    
    // Set font properties
    ctx.font = '14px Arial';
    ctx.fillStyle = '#808080';
    ctx.textAlign = 'left'; 
    //console.log('显示调整参数x:'+String(x)+' y:'+String(y));
    // Render the text
    ctx.fillText('X: ' + x + ', Y: '+y+' ('+showText+')' , 20, 8);
  }

    // Function to handle mouse movement within the canvas
  function handleMouseMove(event) {
    var rect = canvas.getBoundingClientRect();
    var x = event.clientX - rect.left;
    var y = event.clientY - rect.top;
    
    iconVisible = true; // Show the icon
    drawIcon(x, y);
  }

  // Function to hide the icon when the mouse leaves the canvas
  function handleMouseLeave() {
    iconVisible = false;
    ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
  }


// 设置阴影的函数
function setShadow(shadowColor, shadowBlur, shadowOffsetX, shadowOffsetY) {
    ctx.shadowColor = shadowColor;
    ctx.shadowBlur = shadowBlur;
    ctx.shadowOffsetX = shadowOffsetX;
    ctx.shadowOffsetY = shadowOffsetY;
  }

  // 绘制带阴影的矩形的函数
  function drawShadowedRect(x, y, width, height, shadowColor, shadowBlur, offsetX, offsetY, fillColor) {
    setShadow(shadowColor, shadowBlur, offsetX, offsetY);
    ctx.fillStyle = fillColor;
    ctx.fillRect(x, y, width, height);
    // 重置阴影，以便之后的绘制不会受到影响
    setShadow('rgba(0, 0, 0, 0)', 0, 0, 0);
  }

function updateForSellMerging()
  {
    	//调整后列新父亲单元格
      var parentRow = -1;
              var parentCol = -1;
              var parentRowSpan=0;
              var parentColSpan=0
            

              //console.log("================================调整父单元格属性");
            jsonData.forEach(function(rowData, rowIndex) {
        					rowData.cells.forEach(function(cell, cellIndex) {
                    // console.log("第:"+rowIndex+" 行 ，"+cellIndex+" 列 x:"+cell.x+" y:"+cell.y+
                    // " width:"+cell.width+" height:"+cell.height+" showing:"+cell.showBorder+
                    // " ParentRow:"+cell.parentRow+" parentCol:"+cell.parentCol+
                    // " has rowspan:"+cell.rowspan+" has colspan:"+cell.colspan
                    // );
                    if(cell.showBorder==false)
                    {
                      	parentRow = cell.parentRow;
						            parentCol = cell.parentCol;
                    		if(parentRow>=0&&parentCol>=0)//父亲单元格有跨度
												{
										  			var currentSelectCellOn=jsonData[currentSelectedCellRowIndex].cells[currentSelectedCellIndex];//得到光标所在的单元格
										 			  var parentCell=jsonData[parentRow].cells[parentCol];	
								
										  			//获取父亲单元格的跨度
										  				parentRowSpan=jsonData[parentRow].cells[parentCol].rowspan;
										  				parentColSpan=jsonData[parentRow].cells[parentCol].colspan;	
                              
                              var parentHeight=0;
              								var parentWidth=0;
										  			//计算出跨度的高度
										  			for(let m=parentRow;m<=parentRow+parentRowSpan;m++)
														{
                              parentHeight+=jsonData[m].cells[parentCol].height;
														}
                         

										  			for(let n=parentCol;n<=parentCol+parentColSpan;n++)
														{
                              parentWidth+=jsonData[parentRow].cells[n].width;
														}
                            jsonData[parentRow].cells[parentCol].mWidth=parentWidth;
                            jsonData[parentRow].cells[parentCol].mHeight=parentHeight;
                            
													//	console.log("parent Width="+parentWidth+" parent Height="+parentHeight);
										  		//	console.log('isFatherCellUnderSelectedCell  currentSelectCellOn.y:'+currentSelectCellOn.y+' + currentSelectCellOn.height:'+currentSelectCellOn.height+ 
									  			//							' ='+String(currentSelectCellOn.y+currentSelectCellOn.height)+"  parentCell.y:"+parentCell.y+" + parentCell.mHeight: "+parentCell.mHeight+" = "+String(parentCell.y+parentCell.mHeight));
									
										 		
										

												}

                    }
       					 });
      					});
  }

  // 绘制带阴影的页面背景
  drawShadowedRect(pageX, pageY, pageWidth, pageHeight, 'rgba(0, 0, 0, 0.5)', 10, 5, 5, 'white');


	
	saveState()
    //统计更新表格总宽度
    for(var i=0; i<jsonData.length; i++)
    {
      for(var j=0; j<jsonData[i].cells.length; j++)
      {
        var cell = jsonData[i].cells[j];
        var content = cell.content;
        var width = cell.width;
        var height = cell.height;
        var borderSize = cell.borderSize;
        var showBorder = cell.showBorder;
        lastTableTotalWidth+=width;
      }
      break;
    }


    // 绑定删除最后一行按钮的点击事件
		$('#deleteLastRow').click(function() {
  	jsonData.pop(); // 删除最后一行
    saveState()
    console.log("剩余行数: " + jsonData.length); // 打印剩余的行数
    tableRows=jsonData.length;
    tableLines=jsonData.length;
 

    updateTotalHeight();// 重新计算表格总高度
    whereCallDrawTable=" 删除表格最后一行重绘!";
  	redraw(); // 重新绘制表格
		});

// 绑定删除最后一列按钮的点击事件
$('#deleteLastColumn').click(function() {

  
  jsonData.forEach(row => {
    row.cells.pop(); // 每一行删除最后一个单元格
  });

    tableRows=jsonData[0].cells.length;
    saveState()

    console.log("剩余列数: " + (jsonData[0].cells.length)); // 假设所有行的列数相同，打印剩余的列数
    updateTotalWidth();// 重新计算表格总宽度
    updateTotalHeight();// 重新计算表格总高度
    whereCallDrawTable=" 删除表格列重绘!";
     redraw(); // 重新绘制表格
});



    function drawTableOnCanvas(rows, cols) {
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');

    // Calculate cell width and height
    var cellWidth = canvas.width / cols;
    var cellHeight = canvas.height / rows;

    // Clear the canvas before drawing
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw the table
    for (var i = 0; i < rows; i++) {
      for (var j = 0; j < cols; j++) {
        var x = j * cellWidth;
        var y = i * cellHeight;
        
        // Draw cell border
        ctx.strokeRect(x, y, cellWidth, cellHeight);

        // Fill cell with text
        ctx.textAlign = "center";
        ctx.textBaseline = "middle";
        var text = 'Cell ' + (i+1) + ',' + (j+1);
        ctx.fillText(text, x + cellWidth / 2, y + cellHeight / 2);
      }
    }
  }


    //参数：表格数据，修改行号，新的行高
    function adjustTableCellHeight(adjustData,lineNo,newCellHeight)
    {
     
      extHeightFlag=false;//置位，防止重复操作
      let myTotalHeight=0;
      //console.log("调整行号：",lineNo," 新行高：",newCellHeight)
     
      for(var n=0;n<adjustData.length;n++)
      {       
          let tempSells=adjustData[n]; 
          //上一行的高度作为下一行的开始：         

          if(lineNo==n)
          {
              for(var m=0;m<tempSells.cells.length;m++)
              {
              
               
                // tempSells.cells[m].y=myTotalHeight;
                tempSells.cells[m].nheight=newCellHeight;
      
              }

            break;

          } 
          
      }	
      
      //处理完行高后，要处理合并单元格的高度，还是要判断行高调整是否涉及到了周边的单元格。

    }

    //重新调整每行的Y坐标
    function updateTableForAdjustHeight(adjustData)
    {
      let myTotalHeight=0;
     
      //更新所有变更单元格高度
      //从第0行开始：
      for(var n=0;n<adjustData.length;n++)
      {       
          let tempSells=adjustData[n]; 
          //上一行的高度作为下一行的开始：
        
          //判断高度更新标识是否定义，如有定义判断是否大于0
          if (tempSells.cells[0].height !== undefined) 
          {

            if(tempSells.cells[0].nheight>0)
            {
              //console.log("更新单元格高度 当前所在行：",n);
              let currentLineHeight=tempSells.cells[0].nheight;
              for(var m=0;m<tempSells.cells.length;m++)
              { 
                tempSells.cells[m].height=currentLineHeight;
                tempSells.cells[m].nheight=0; //标识置位
                //console.log("更新单元格高度 当前所在列：",m," 高度：",tempSells.cells[m].height);

              }
             
            }           
            else //无变更
            {

            }
           
          

          }
            
      }	
      //修正Y坐标
      //console.log("修正Y坐标--------------------------------------------.>");
      for(var l=0;l<adjustData.length;l++)
      {
        let tempSells=adjustData[l];
       // console.log("更新单元格Y 当前所在行：",l," 高度：",tempSells.cells[l].height);
       
        if(l>0)
        {
          for(var n=0;n<tempSells.cells.length;n++)
          {
            tempSells.cells[n].y=myTotalHeight;
            //console.log("更新单元格Y 当前所在列：",m," 高度：",tempSells.cells[n].height," Y:",tempSells.cells[n].y);
          }
          
        
        } 
        myTotalHeight=myTotalHeight+tempSells.cells[0].height;

      }

    ///////////////////////////
    //修正合并单元格

    for(var p=0;p<adjustData.length;p++)
    {
      let tempSells=adjustData[p];
      for(var q=0;q<tempSells.cells.length;q++)
      {
          if(tempSells.cells[q].rowspan>0)
          {
            //console.log(" 合并单元格跨行数：",tempSells.cells[q].rowspan);
            let magCellHeight=0;
            for(var r=0;r<=tempSells.cells[q].rowspan;r++)
            {
              magCellHeight+=adjustData[p+r].cells[0].height;
             // console.log(" 当前行：",r+p," 行高：",adjustData[p+r].cells[0].heigh," 累计高度:",magCellHeight);

            }
            tempSells.cells[q].mHeight=magCellHeight;

          }
      }
   
 
    }

    //修正合并单元格完成///////////////////////////

    }


    function drawTable(m_table_data) {
  

      let hasAdjectHeight=false;
      canvasOffset = $('#myCanvas').offset(); 
      var myCellCanvas = document.getElementById('cellsCanvas');
      var ctxCellCanvas = myCellCanvas.getContext('2d');

                //myCellCanvas = document.getElementById('cellsCanvas');
              // ctxCellCanvas = myCellCanvas.getContext('2d');
      var tableCanvas = document.getElementById('myCanvas');
             //console.log(tableCanvas);
      var ctxTables = tableCanvas.getContext('2d');

      cellStartX = tableOffsetX;
      cellStartY = tableOffsetY;
      var alignTypes = ['left', 'center', 'right'];
			var selectCellCounters=0;
      for(var n=0;n<jsonData.length;n++)
      {
        let tempSells=jsonData[n];
        for(var m=0;m<tempSells.cells.length;m++)
        {
         
          if(tempSells.cells[m].selected==true)
          selectCellCounters++;
        

        }
        
      }		
  

      // 遍历表格数据，行数据
      // var rows = data.length;
      // var cols = data[0].cells.length;
      let firstCell=true;
      jsonData.forEach(function(rowData, rowIndex) {
        rowData.cells.forEach(function(cell, cellIndex) {
          var x = cellStartX + cell.x;
          var y = cellStartY + cell.y;   
          if(rowData>0||cellIndex>0)
          firstCell=false;     
    
          if(cell.showBorder==true)
          {
            ctxTables.beginPath();

            if(cell.colspan>=1||cell.rowspan>=1)  //处理已合并的单元格。编辑区域扩张
            {
              ctxTables.rect(x, y, cell.mWidth, cell.mHeight);

              textData=cell;
              textData.text=cell.content;       
                
              myCellCanvas = document.getElementById('cellsCanvas');
              //console.log(myCellCanvas); // 这应该显示具体的canvas元素信息，而不是null或undefined
              if (myCellCanvas&&textData.text!="") {
              // console.log ("111111111111 textX:"+textX," textY:"+textY, " cellStartX:",cellStartX," cellStartY:",cellStartY);
              myCellCanvas.style.left=x+"px";
              myCellCanvas.style.top =y+"px";
              myCellCanvas.width=cell.mWidth;
              myCellCanvas.height=cell.mHeight;    
              compressStyles();
              
              generateLinesData();
              textData.cursorVisible=false;  
              
              where_to_call="drawTable 01 cell.showBorder==true"+ " 原始调用:"+whereCallDrawTable;
              renderText();		
              }
            }
            else
            {
                //还有一种可能，当前单元格已被吞并，不需要再显示。
                if(cell.parentCol>=0&&cell.parentCol>=0)
                {
                  //什么也不做

                }
                else
                {
                  ctxTables.rect(x, y, cell.width, cell.height);      
                  textData=cell;
                  textData.text=cell.content;
                 
                  myCellCanvas = document.getElementById('cellsCanvas');
                  //console.log(myCellCanvas); // 这应该显示具体的canvas元素信息，而不是null或undefined
                  if (myCellCanvas&&textData.text!="") {
                  // console.log ("222222222222 textX:"+x," textY:"+y, " w:",cell.width,"  h:",cell.height);
                  myCellCanvas.style.left=x+"px";
                  myCellCanvas.style.top =y+"px";
                  myCellCanvas.width=cell.width;
                  myCellCanvas.height=cell.height;    
                  compressStyles();
                  
                  generateLinesData();
                  textData.cursorVisible=false;   
                  where_to_call="drawTable 02 未被合并的单元格渲染"+ " 原始调用:"+whereCallDrawTable;;
                  renderText();	
                  if(extHeightFlag==true)//如果文本超过画布的高度
                  {
                    adjustTableCellHeight(jsonData,rowIndex,totalCellHeight);
                    hasAdjectHeight=true;
                    
                 
                  }
                 

                }
                
                
              }


            }
           
            
            ctxTables.fillStyle = selectCellCounters>=2&&cell.selected ? 'lightblue' : 'white';
              // 设置字体样式
        			ctxTables.font = '16px Microsoft YaHei';
       			

            //ctx.fill();//透明背景
            if (cell.showBorder) {
              ctxTables.lineWidth = cell.borderSize;
              ctxTables.textBaseline = 'middle';
             
              ctxTables.strokeStyle = 'black';
              ctxTables.stroke();
            }
           
             //console.log("Q89: editor_locked_cellRecord.columns:",editor_locked_cellRecord.columns," editor_locked_cellRecord.columns:",editor_locked_cellRecord.rows," rowIndex:",rowIndex," cellIndex:",cellIndex);
             //console.log("Q89 isInScrolling:",isInScrolling)
             if((editor_locked_cellRecord.columns!=cellIndex||editor_locked_cellRecord.rows!=rowIndex)||isInScrolling===true)//当前非编辑时
            {        

             // 将第一个画布的内容复制到第二个画布
             if(myCellCanvas&&myCellCanvas.width>0&&myCellCanvas.height>0)
             ctxTables.drawImage(myCellCanvas, x, y); // 复制到第二个画布的上
             
            }
            else
            {
            //    cellStartX = canvasOffset.left+tableOffsetX;
            // cellStartY = canvasOffset.top+tableOffsetY;

            //     var cell_X = cellStartX + cell.x;
            //     var cell_Y = cellStartY + cell.y;  		


                lastSizeOfCellCanvas.left=(x+canvasOffset.left)+"px";
                lastSizeOfCellCanvas.top=(y+canvasOffset.top)+"px";
                lastSizeOfCellCanvas.width=cell.width;    
								lastSizeOfCellCanvas.height= cell.height;

            }

            ctxTables.strokeStyle = 'black';

            ctxTables.textBaseline = 'middle';
            ctxTables.textAlign = 'left';
     


          }
          
          
        });
       
        
      });

      if(hasAdjectHeight==true)
      {
        updateTableForAdjustHeight(jsonData);
       
        return;
      }
      finishDrawTable=true;

         myCellCanvas = document.getElementById('cellsCanvas');
        if(lastTextData!=null)
        {
          textData=lastTextData;
          //console.log("Q9 loadAtFirstTime:", loadAtFirstTime);
          if(loadAtFirstTime)
          {
            //console.log ("Q99999999999999999 第一次隐藏888");
            myCellCanvas.style.display = 'none';
            return;

          }

          if (myCellCanvas&&textData.text!=""&&isInScrolling==false) {
            //console.log ("Q8888888888888888888 text:"+textData.content," lastSizeOfCellCanvas.left:"+lastSizeOfCellCanvas.left, " lastSizeOfCellCanvas.top:",lastSizeOfCellCanvas.top," cellStartY:",cellStartY);
            // myCellCanvas.style.left=1500+"px";                       
            // myCellCanvas.style.top =200+"px";
            myCellCanvas.style.display = 'block';
            myCellCanvas.style.left=lastSizeOfCellCanvas.left;                       
            myCellCanvas.style.top =lastSizeOfCellCanvas.top;
            myCellCanvas.width=lastSizeOfCellCanvas.width;
            myCellCanvas.height=lastSizeOfCellCanvas.height;    
            myCellCanvas.style.zIndex=9999;
            compressStyles();
            generateLinesData();
            textData.cursorVisible=false;
            where_to_call="drawTable 03  (myCellCanvas&&textData.text!=\"\"&&isInScrolling==false)";
            renderText();		
            finishDrawTable=true;
           
            }
          }
          else
          { finishDrawTable=true;
           
           // console.log ("Q98888888888888888888 我没点点点");
            if(loadAtFirstTime)
            {
              //console.log ("Q99999999999999999 第一次隐藏");
              myCellCanvas.style.display = 'none';
              return;
  
            }
          }
          isInScrolling=false;
         
         // console.log("QQ44::finishDrawTable-----------------55555--------------------------------");
    }

 
    //这是一个临时画布,用于计算表切割位（参数:数据,页面高,可放置的容量
    function  drawTableCells( m_table_data,restOffCurrentPageSpace) {
      upstairs_cells_height=0;
      cellsCompareData=[];//列比对数据
      current_columns_index=0;
      segmentHeight=0;
      maxTextHeight=0;
     
     
      let lastCellsTotalOfHeight=0; //处理之前的单元格高度之和
      //算法:用接近法,获取最大完整切面的位置.
 
      

      //切割位置,由表行开始,每一行的开始,就会知道当前行是不是初切割的对象
      //步骤:
      //1.在line遍历过程中判断所在行高度
      //2.在横切单元行上逐个单元格渲染
      //3.在渲染单元格时逐行判断,是否是最后一个完整行,如果是,退出循环
      var tableCanvas = document.createElement('canvas');
      //console.log("QQ:2211:tableCanvas",tableCanvas," restOffCurrentPageSpace:",restOffCurrentPageSpace);
      // 将canvas元素设为隐藏
  	  //canvas.style.display = 'none';

   
      // 设定canvas元素的宽和高
      tableCanvas.width = 800;
      tableCanvas.height = 9000;	
    
      var myCellCanvas = document.getElementById('cellsCanvas');
      var ctxCellCanvas = myCellCanvas.getContext('2d');
      var ctxTables = tableCanvas.getContext('2d');

      cellStartX = 0;
      cellStartY = 0;
      var alignTypes = ['left', 'center', 'right'];
			var selectCellCounters=0;
     
  

      // 遍历表格数据，行数据
      // var rows = data.length;
      // var cols = data[0].cells.length;
      let firstCell=true;
      hasToCutCells=false;
      let lastCuttingCellRowIndex=-1;//记录被切割断的表格行索引
      current_columns_index=0;
      //1.在line遍历过程中判断所在行高度
 			segmentHeight=restOffCurrentPageSpace;
       let current_table_cell_total_height=0;
       let current_table_cell_singleLineHeight=0;
      jsonData.forEach(function(rowData, rowIndex) {
        
        scan_Global_RowOfTable=rowIndex;
        let currentLineMaxHeight=rowData.cells[0].height;//当前行的高度


				//单元格高度大于当前页面可容纳的高度时,认为是被切割的对像,告知自然段渲染时要作相对应的标识.
          if(rowIndex==0)
          {          
                lastCuttingCellRowIndex=rowIndex;
                single_table_cell_index=rowIndex;
                
                if(lastCellsTotalOfHeight>segmentHeight)
                  {
                    hasToCutCells=true;
                  console.log("QQ:111:#---#文高大于容量！！");

                  }                 
                lastCellsTotalOfHeight+=currentLineMaxHeight;//如果不大于指定的区域暂才认为是过了
            
    
        
             // console.log("QQ:1111:### 已绘列高:",lastCellsTotalOfHeight,"当前行高是:",currentLineMaxHeight," 当前遍历行数:",rowIndex," 可用表格容量:",restOffCurrentPageSpace," text:",rowData.cells[0].text);
          }
       

         

          current_columns_index=0;
   

        // rowData.cells.forEach(function(cell, cellIndex) {
        for (let cellIndex = 0; cellIndex < rowData.cells.length; cellIndex++) 
        {
            let cell = rowData.cells[cellIndex];
            var x = cellStartX + cell.x;
            var y = cellStartY + cell.y;   	

            current_columns_index++;

              if(rowData>0||cellIndex>0)
              firstCell=false;     
              if(cellIndex==0)
              {
                current_table_cell_singleLineHeight=cell.height;
                

              }
          if(cell.showBorder==true)
          {
            ctxTables.beginPath();
             
           

            if(cell.colspan>=1||cell.rowspan>=1)  //处理已合并的单元格。编辑区域扩张
            {
              ctxTables.rect(x, y, cell.mWidth, cell.mHeight);

              textData=cell;
              textData.text=cell.content;       
                
              myCellCanvas = document.getElementById('cellsCanvas');
              //console.log("QQ:1111:",myCellCanvas); // 这应该显示具体的canvas元素信息，而不是null或undefined
              if (myCellCanvas&&textData.text!="") {
              // console.log ("111111111111 textX:"+textX," textY:"+textY, " cellStartX:",cellStartX," cellStartY:",cellStartY);
              myCellCanvas.style.left=x+"px";
              myCellCanvas.style.top =y+"px";
              myCellCanvas.width=cell.mWidth;
              myCellCanvas.height=cell.mHeight;    
              compressStyles();
              
              generateLinesData();
              textData.cursorVisible=false;  
              where_to_call="drawTableCells 05 合并过的单元格";
              renderText();		
              if(hasNoEnoughSpacing==true) //首行不够空间
              {
                currentPage++;
                hasNoEnoughSpacing=false;
                console.log("QQ:1111:### 单元格首行跳出"," rowIndex:",rowIndex, " cellIndex:",cellIndex);
                break;
              }

              //console.log("QQ:1111:### 合并过的单元格"," upstairs:",upstairs_cells_height);
              }
            }
            else
            {
                //还有一种可能，当前单元格已被吞并，不需要再显示。
                // if(cell.parentCol>=0&&cell.parentCol>=0)
                // {
                //   //什么也不做
                //   console.log("QQ:111  这个单元格被合并过了: " ,current_table_cell_total_height," segmentHeight:",segmentHeight);
                  
                  
                 


                // }
                // else//在这里绘制单元格内容
                {
                  ctxTables.rect(x, y, cell.width, cell.height);      
                  textData=cell;
                  textData.text=cell.content;   
                  myCellCanvas = document.getElementById('cellsCanvas');
                  //console.log(myCellCanvas); // 这应该显示具体的canvas元素信息，而不是null或undefined
                  if (myCellCanvas&&textData.text!="") {
                  // console.log ("222222222222 textX:"+x," textY:"+y, " w:",cell.width,"  h:",cell.height);
                  myCellCanvas.style.left=x+"px";
                  myCellCanvas.style.top =y+"px";
                  myCellCanvas.width=cell.width;
                  myCellCanvas.height=cell.height;    
									//在绘制单元格前,就可以用cell.height的高度判读这个区域是否要截断处理了,如果不需要就直接跳过单元格内部的文字渲染。
                  //current_table_cell_total_height 累计已绘的表格单元格行
                    //  if(cellIndex==0)//在第0列是处理当前行
                    //   {

                    //     current_table_cell_singleLineHeight=cell.height;
                       
                    //   }
                       //当前绘制的单元格已经超过了当前页的高度容量,要去计算当前单元格内容的真实高度
                       //var single_table_cell_index=0; 
                       single_table_cell_index=cellIndex; //在绘制表格过程判断当前行有可能出现跨页的情况，需要记录当前行的单元格的索引,标识当前哪一列正在绘制
                                                          //当整行绘制完成后，会将这几列的真实高度作为参考比较.哪列触发了切口文字完整性计算
                     
                       if((upstairs_cells_height+current_table_cell_singleLineHeight)>segmentHeight)//开始渲染在预期内的单元格,采集各个单元格文本切割前的高度与及切害时的位置信息
                        {

                         // console.log("QQ:2211  判断当前行有可能出现跨页的情况,行高: " ,current_table_cell_total_height," segmentHeight:",segmentHeight," index:",cellIndex," upstairs_cells_height:",upstairs_cells_height);
                          compressStyles();                  
                          generateLinesData();
                          textData.cursorVisible=false;   
                          where_to_call="drawTableCells 06判断当前行有可能出现跨页的情况";
                          renderText();	

                          if(hasNoEnoughSpacing==true) //首行不够空间
                          {
                            currentPage++;
                            hasNoEnoughSpacing=false;
                            console.log("QQ:1111: 111 ### 单元格首行跳出"," rowIndex:",rowIndex, " cellIndex:",cellIndex);
                            break;
                          }
                  
                        }     
                        else{
                         // console.log("QQ:1111  判断当前行有可能出现跨页的情况,行高(按表单元格行累加): " ,current_table_cell_total_height," segmentHeight:",segmentHeight," index:",cellIndex," upstairs_cells_height:",upstairs_cells_height);
                        }        
                }
              }
            }
           
            
            ctxTables.fillStyle = selectCellCounters>=2&&cell.selected ? 'lightblue' : 'white';
              // 设置字体样式
        			ctxTables.font = '16px Microsoft YaHei'; 
            //ctx.fill();//透明背景
            if (cell.showBorder) {
              ctxTables.lineWidth = cell.borderSize;
              ctxTables.textBaseline = 'middle';             
              ctxTables.strokeStyle = 'black';
              ctxTables.stroke();
            }
             if((editor_locked_cellRecord.columns!=cellIndex||editor_locked_cellRecord.rows!=rowIndex)||isInScrolling===true)//当前非编辑时
            {        

             // 将第一个画布的内容复制到第二个画布
             if(myCellCanvas&&myCellCanvas.width>0&&myCellCanvas.height>0)
             ctxTables.drawImage(myCellCanvas, x, y); // 复制到第二个画布的上
             
            }
            else
            {
                lastSizeOfCellCanvas.left=(x+canvasOffset.left)+"px";
                lastSizeOfCellCanvas.top=(y+canvasOffset.top)+"px";
                lastSizeOfCellCanvas.width=cell.width;    
								lastSizeOfCellCanvas.height= cell.height;

            }

            ctxTables.strokeStyle = 'black';
            ctxTables.textBaseline = 'middle';
            ctxTables.textAlign = 'left';
          }          
          
            if(hasNoEnoughSpacing==true) //首行不够空间
            {
							currentPage++;
              hasNoEnoughSpacing=false;
              console.log("QQ:1111:444### 单元格首行跳出"," rowIndex:",rowIndex, " cellIndex:",cellIndex);
              break;
            }
        };
        //按行累计表每行的高,current_table_cell_singleLineHeight已在第0列时获得当前行高的值. 
        
        //console.log("QQ:1111  current_table_cell_total_height: " ,current_table_cell_total_height," upstairs_cells_height:",upstairs_cells_height," segmentHeight:",segmentHeight," current_table_cell_singleLineHeight:",current_table_cell_singleLineHeight," lastSegmentPosition:",lastSegmentPosition," rowIndex:",rowIndex);
        upstairs_cells_height+=current_table_cell_singleLineHeight;
        current_table_cell_total_height+=current_table_cell_singleLineHeight;

        if(current_table_cell_total_height>segmentHeight)//单元格大于了表格,就要翻页. 此时当前页的文本行高度不一定是整个segmentHeight的高度。可能是小于它的,所以要从上面绘制的单元格组中获取
        {
          //console.log("QQ:1112 完成切割屏后显示切片信息:",segment_Info.length);
            for (var i = 0; i < segment_Info.length; i++) 
            {
            var segment = segment_Info[i];
            lastSegmentPosition=segment.height;
           // console.log("QQ:1112 切口 " + (i + 1) + "：","segment_index: " + segment.segment_index," offset_X: " + segment.offset_X," offset_Y: " + segment.offset_Y," width: " + segment.width,"  height: " + segment.height);
           }

        }
          // if(hasToCutCells==true)
          // {
            
          //   //console.log("QQ:134: end of line ::::::maxTextHeight:",maxTextHeight," lastCellsTotalOfHeight:",lastCellsTotalOfHeight);


          //   // if(hasToCutCells==true)
          //   //   {
          //   //       cellsCompareData.push({
          //   //           textHeight: totalTextHeight,
          //   //           segmentHeight: segmentHeight,
          //   //           cellsHeight: tempSegmentPosition,
          //   //           columnsIndex: current_columns_index
          //   //       });
          //   //       console.log("QQ99: cellsHeight",tempSegmentPosition," segmentHeight:",segmentHeight);
      
          //   //   }
          //   //console.log("QQ5: cellsCompareData:",cellsCompareData.length," data:",cellsCompareData);
          //   //lastSegmentPosition=0;
          //   // for( let x=0;x<cellsCompareData.length;x++)
          //   //   {
          //   //     lastSegmentPosition=cellsCompareData[x].cellsHeight>lastSegmentPosition?cellsCompareData[x].cellsHeight:lastSegmentPosition;//收集最大的有效高度
          //   //     console.log("QQ:111 比对各列的各个数据高: textHeight:",cellsCompareData[x].textHeight," cellsHeight:",cellsCompareData[x].cellsHeight," columnsIndex:",cellsCompareData[x].columnsIndex);
          //   //   }

           


          //     //hasToCutCells=false;
          //     //console.log("QQ:2211: 当前页有效文字高度:",lastSegmentPosition);
           

          // }
          
      });

     

            // 将canvas内容转换为data URL
      var dataURL = tableCanvas.toDataURL('image/png');

      // 创建一个下载链接
      var downloadLink = document.createElement('a');
      downloadLink.href = dataURL;
      downloadLink.download = 'canvas-image.png';

      // 触发下载
      // 使用JavaScript创建一个点击事件
      // 这个事件不需要用户实际点击链接
      downloadLink.dispatchEvent(new MouseEvent('click', {
        'bubbles': true,
        'cancelable': true,
        'view': window
      }));

      //console.log("QQ8::finishDrawTable---------222----------------------------------------");
         myCellCanvas = document.getElementById('cellsCanvas');
        if(lastTextData!=null)
        {
          textData=lastTextData;
          //console.log("Q9 loadAtFirstTime:", loadAtFirstTime);
          if(loadAtFirstTime)
          {
            //console.log ("Q99999999999999999 第一次隐藏888");
            myCellCanvas.style.display = 'none';
            return;

          }

          if (myCellCanvas&&textData.text!=""&&isInScrolling==false) {
            //console.log ("Q8888888888888888888 text:"+textData.content," lastSizeOfCellCanvas.left:"+lastSizeOfCellCanvas.left, " lastSizeOfCellCanvas.top:",lastSizeOfCellCanvas.top," cellStartY:",cellStartY);
            // myCellCanvas.style.left=1500+"px";                       
            // myCellCanvas.style.top =200+"px";
            myCellCanvas.style.display = 'block';
            myCellCanvas.style.left=lastSizeOfCellCanvas.left;                       
            myCellCanvas.style.top =lastSizeOfCellCanvas.top;
            myCellCanvas.width=lastSizeOfCellCanvas.width;
            myCellCanvas.height=lastSizeOfCellCanvas.height;    
            myCellCanvas.style.zIndex=9999;
            compressStyles();
            generateLinesData();
            textData.cursorVisible=false;
            where_to_call="drawTableCells 07判断当前行有可能出现跨页的情况";
            renderText();		
            finishDrawTable=true;
            //console.log("QQ:111::finishDrawTable---------33333----------------------------------------");
            }
          }
          else
          { finishDrawTable=true;
            //console.log("QQ8::finishDrawTable---------4444----------------------------------------");
           // console.log ("Q98888888888888888888 我没点点点");
            if(loadAtFirstTime)
            {
              //console.log ("Q99999999999999999 第一次隐藏");
              myCellCanvas.style.display = 'none';
              return;
  
            }
          }
          isInScrolling=false;
         
          //console.log("QQ8::finishDrawTable-----------------55555--------------------------------");
    }

    //这是一个临时画布,用于计算表切割位（参数1:m_para_data自然段数据,参数2：restOffCurrentPageSpace,可用的容量，页面被用了部分，剩余可放置的页面容量高)
    function drawParaCells(m_para_data,restOffCurrentPageSpace,m_sn) {
  
      m_para_data.content=m_para_data.text;
      cellsCompareData=[];//列比对数据
      segment_Info=[];//画布切分线
      current_columns_index=0;
      let lastCellsTotalOfHeight=0; //处理之前的单元格高度之和
      let offsetAndStartY=985-restOffCurrentPageSpace;
      //算法:用接近法,获取最大完整切面的位置.
 
      debugSN=m_sn;

      //切割位置,由表行开始,每一行的开始,就会知道当前行是不是初切割的对象
      //步骤:
      //1.在line遍历过程中判断所在行高度
      //2.在横切单元行上逐个单元格渲染
      //3.在渲染单元格时逐行判断,是否是最后一个完整行,如果是,退出循环
      
    
      var myCellCanvas = document.getElementById('cellsCanvas');
      var ctxCellCanvas = myCellCanvas.getContext('2d');


      cellStartX = 0;
      cellStartY = 0;
      var alignTypes = ['left', 'center', 'right'];
			var selectCellCounters=0;

  

     
      let firstCell=true;
      hasToCutCells=false;
      let lastCuttingCellRowIndex=-1;//记录被切割断的表格行索引
      current_columns_index=0;
    
        //1.在line遍历过程中判断所在行高度
 			  segmentHeight=restOffCurrentPageSpace;
        let currentLineMaxHeight=m_para_data.height;//当前行的高度
        
       //console.log("QQ:1112:当前行高是",currentLineMaxHeight," 可用表格容量:",restOffCurrentPageSpace);

				//单元格高度大于当前页面可容纳的高度时,认为是被切割的对像,告知自然段渲染时要作相对应的标识.
          if(currentLineMaxHeight>restOffCurrentPageSpace) 
          {
            
            hasToCutCells=true;
            
          
          }
          else
          {
            lastCellsTotalOfHeight+=currentLineMaxHeight;//如果不大于指定的区域暂才认为是过了
          }


         

          current_columns_index=0;

          var x =0;
          var y =0;   


              textData=m_para_data;
              textData.text=m_para_data.content;       
                
              myCellCanvas = document.getElementById('cellsCanvas');
              //console.log(myCellCanvas); // 这应该显示具体的canvas元素信息，而不是null或undefined
              if (myCellCanvas&&textData.text!="") {
             //console.log ("111111111111 textX:"+textX," textY:"+textY, " cellStartX:",cellStartX," cellStartY:",cellStartY);
              myCellCanvas.style.left=x+"px";
              myCellCanvas.style.top =y+"px";
              myCellCanvas.width=m_para_data.width;
              myCellCanvas.height=m_para_data.height;    
              compressStyles();
              showParaInCellEdit=true;
              generateLinesData();
              textData.cursorVisible=false;  
              where_to_call="drawParaCells 08";
              
              //console.log("QQ:1113:当前行高是",currentLineMaxHeight," 渲染前计算可用表格容量:",segmentHeight," sn:",m_sn); 
              
              renderText();		
           
              showParaInCellEdit=false;
             
             
             
              }

     
              //console.log("QQ:133: cellsCompareData:",cellsCompareData.length," data:",cellsCompareData," segment_Info:",segment_Info);
              lastSegmentPosition=0;
              for( let x=0;x<cellsCompareData.length;x++)
                {
                  lastSegmentPosition=cellsCompareData[x].cellsHeight>lastSegmentPosition?cellsCompareData[x].cellsHeight:lastSegmentPosition;//收集最大的有效高度
                  //console.log("QQ:133: textHeight:",cellsCompareData[x].textHeight," cellsHeight:",cellsCompareData[x].cellsHeight," columnsIndex:",cellsCompareData[x].columnsIndex);
                }
       
        
          if(hasToCutCells==true)
          {            
            //console.log("QQ33: end of line ::::::maxTextHeight:",maxTextHeight," lastCellsTotalOfHeight:",lastCellsTotalOfHeight," m_para_data:",m_para_data);
            // if(hasToCutCells==true)
            //   {
            //       cellsCompareData.push({
            //           textHeight: totalTextHeight,
            //           segmentHeight: segmentHeight,
            //           cellsHeight: tempSegmentPosition,
            //           columnsIndex: current_columns_index
            //       });
            //       console.log("QQ99: cellsHeight",tempSegmentPosition," segmentHeight:",segmentHeight);
      
            //   }
            //hasToCutCells=false;
            //console.log("QQ:1112: 当前页有效文字高度:",lastSegmentPosition," 当前页面容量是:",restOffCurrentPageSpace," 文本框高:",m_para_data.height);
           // return;

          }
          
    

     


      //console.log("QQ33::finishDrawTable---------222----------------------------------------");
         myCellCanvas = document.getElementById('cellsCanvas');
        if(lastTextData!=null)
        {
          textData=lastTextData;
          //console.log("Q9 loadAtFirstTime:", loadAtFirstTime);
          if(loadAtFirstTime)
          {
            //console.log ("Q99999999999999999 第一次隐藏888");
            myCellCanvas.style.display = 'none';
            return;

          }

          if (myCellCanvas&&textData.text!=""&&isInScrolling==false) {
            //console.log ("Q8888888888888888888 text:"+textData.content," lastSizeOfCellCanvas.left:"+lastSizeOfCellCanvas.left, " lastSizeOfCellCanvas.top:",lastSizeOfCellCanvas.top," cellStartY:",cellStartY);
            // myCellCanvas.style.left=1500+"px";                       
            // myCellCanvas.style.top =200+"px";
            myCellCanvas.style.display = 'block';
            myCellCanvas.style.left=lastSizeOfCellCanvas.left;                       
            myCellCanvas.style.top =lastSizeOfCellCanvas.top;
            myCellCanvas.width=lastSizeOfCellCanvas.width;
            myCellCanvas.height=lastSizeOfCellCanvas.height;    
            myCellCanvas.style.zIndex=9999;
            compressStyles();
            generateLinesData();
            textData.cursorVisible=false;
            where_to_call="drawParaCells 09 finishDrawTable";
            //showParaInCellEdit=true;
            renderText();		
            finishDrawTable=true;
            //showParaInCellEdit=false;
            //console.log("QQ33::finishDrawTable---------33333----------------------------------------");
            }
          }
          else
          { finishDrawTable=true;
           // console.log("QQ33::finishDrawTable---------4444----------------------------------------");
           // console.log ("Q98888888888888888888 我没点点点");
            if(loadAtFirstTime)
            {
              //console.log ("Q99999999999999999 第一次隐藏");
              myCellCanvas.style.display = 'none';
              return;
  
            }
          }
          isInScrolling=false;
        
         
          //console.log("QQ33::finishDrawTable-----------------55555--------------------------------");
    }



  //redraw();

function drawTableFromJson(jsonData) { //绘制表格
  var canvas = document.getElementById('myCanvas');
  var ctx = canvas.getContext('2d');
  canvas.width = jsonData[0].cells.reduce((acc, cell) => acc + cell.width, 0);
  canvas.height = jsonData.length * jsonData[0].cells[0].height;
  ctx.clearRect(0, 0, canvas.width, canvas.height);


  //遍历每一行
  jsonData.forEach(function(rowData, rowIndex) {
    rowData.cells.forEach(function(cell) {
      if (cell.showBorder) {      
        ctx.strokeRect(cell.x, cell.y, cell.width, cell.height);
      }
      ctx.textAlign = "center";
      ctx.textBaseline = "middle";  
      ctx.fillText(cell.content, cell.x + cell.width / 2, cell.y + cell.height / 2);
    });
    //currentY += rowData.cells[0].height;
  });
}

// 在变化之前查找表格行列数
function getCRFormCell(x, y,description) 
{
 
     console.log(description+ "x: " + x + ", y: " + y);
     //遍历行
     for (var rowIndex = 0; rowIndex < jsonData.length; rowIndex++) {
       var row = jsonData[rowIndex].cells;
       //遍历列
       for (var cellIndex = 0; cellIndex < row.length; cellIndex++) {
         var cell =jsonData[rowIndex].cells[cellIndex];

        // console.log("遍历 第" + String(rowIndex) + "行第" + String(cellIndex) + "列; X:"+ String(cell.x)+ " Y:"+ String(cell.y)+" w:"+cell.width+" h:"+String(cell.height));

         //判断点击位置是否在单元格内
         if (x >= cell.x && x <= (cell.x + cell.width) &&
             y >= cell.y && y <= (cell.y + cell.height)) {
            console.log("description:"+description + String(rowIndex) + "行第" + String(cellIndex) + "列; X:"+ String(x)+ " Y:"+ String(y));
           return {row:rowIndex, col:cellIndex};
          }//返回单元格坐标
         }
         
       }
       return null;
}
  


// Get cell by coordinates
function getCellByCoords(x, y) {
 
  let offset=0;
      //遍历行
      for (var rowIndex = 0; rowIndex < jsonData.length; rowIndex++) {
        var row = jsonData[rowIndex].cells;
        //遍历列
        for (var cellIndex = 0; cellIndex < row.length; cellIndex++) {
          var cell = row[cellIndex];
          //判断点击位置是否在单元格内
          if (x >= cell.x+offset && x <= (cell.x + cell.width-offset) &&
              y >= cell.y+offset && y <= (cell.y + cell.height-offset)) {
            return cell;//返回单元格坐标
          }
          
        }
       
      }
    return null;
  }

  function updateCellSize(row,col,x,y,w,h)
  {    
    console.log("=====+更新行:"+String(row)+" 列："+String(col)+" 坐标："+String(x)+","+String(y)+" 宽："+String(w)+" 高："+String(h));
        jsonData[row].cells[col].x=x;
        jsonData[row].cells[col].y=y;
        jsonData[row].cells[col].mWidth=w;
        jsonData[row].cells[col].mHeight=h;
        jsonData[row].cells[col].showBorder=true;
            

  }
    function getCellFromCoords(x, y) {
      var startX = 0;
      var startY = 0;
      //遍历行
      for (var rowIndex = 0; rowIndex < jsonData.length; rowIndex++) {
        var row = jsonData[rowIndex].cells;
        //遍历列
        for (var cellIndex = 0; cellIndex < row.length; cellIndex++) {
          var cell = row[cellIndex];
          //判断点击位置是否在单元格内
          if (x >= startX && x <= startX + cell.width &&
              y >= startY && y <= startY + cell.height) {
            return {row: rowIndex, col: cellIndex};//返回单元格坐标
          }
          startX += cell.width;
        }
        startX = 0;
        startY += row[0].height;
      }

      return null;
    }





    function getCellStartX(rowIndex, colIndex)
    {
      var x=0;
      var y=0;
      //遍历行，从0到colIndex
      for (var j = 0; j <colIndex ; j++) {
          x+=jsonData[rowIndex].cells[j].width
        }
      for (var i = 0; i < rowIndex; i++) {
       
          y+=jsonData[i].cells[colIndex].height;
       
      }
      x=x+tableOffsetX;
      y=y+tableOffsetY;
      return {x:x,y:y};
    }


    function redraw() {
      var tableCanvas = document.getElementById('myCanvas');
             //console.log(tableCanvas);
      var ctxTables = tableCanvas.getContext('2d');
      ctxTables.clearRect(0, 0, tableCanvas.width, tableCanvas.height);
      //drawShadowedRect(pageX, pageY, pageWidth, pageHeight, 'rgba(0, 0, 0, 0.5)', 10, 5, 5, 'white');
    
      drawTable(jsonData);
      
     
    }





    function updateTotalWidth()
    {
      tableTotalWidth=0;
      
          for(var m=0;m<jsonData[0].cells.length;m++)
            {
              tableTotalWidth+=jsonData[0].cells[m].width;
            }
    }

    function updateTotalHeight()
    {
           tableTotalHeight=0; //重新计算表格总高
            for(var n=0;n<jsonData.length;n++)
            {
              tableTotalHeight+=jsonData[n].cells[0].height;
            }
    }

    $('#canvasPopup').mousedown(function(e) {
    var rect = canvas1.getBoundingClientRect();
    var x = e.clientX - rect.left;
    var y = e.clientY - rect.top;
    var selected = highlightSquares(x, y);
    
    //alert('Rows selected: ' + selected.rows + ', Columns selected: ' + selected.columns);


    console.log('正在执行  表格 插入操作 Rows selected: ' + selected.rows + ', Columns selected: ' + selected.columns); 
    textData=[];

   
    var jsonData = generateJsonData(selected.rows, selected.columns);
  	//drawTableFromJson(jsonData);
    tableRows=selected.columns;
    tableLines=selected.rows;
    tableColumns=selected.columns;

   

    //更新表格总宽度
    updateTotalWidth(); //重新计算表格总宽度
    updateTotalHeight();//重新计算表格总高度
    lastTableTotalWidth=tableTotalWidth;//记录上一次的表格总宽度
    updateForSellMerging();
    whereCallDrawTable=" 插入表格重绘!";

    redraw();
    // 绘制第二个图层的表格
    // drawTableOnLayer2(selected.rows, selected.columns);
    // 调用函数绘制表格
    //drawTableOnLayer2WithMargins(selected.rows, selected.columns, marginTop, marginBottom, marginLeft, marginRight);
           // 绘制页面边框
           var ctx = canvas1.getContext('2d');
  				ctx.strokeStyle = '#cccccc';
  				ctx.lineWidth = 1;
  				ctx.strokeRect(pageX, pageY, pageWidth, pageHeight);

    $('#canvasPopup').hide(); // 隐藏第一个 canvas 层




  });


    //  drawTable(jsonData);

       // 绘制页面边框
  ctx.strokeStyle = '#cccccc';
  ctx.lineWidth = 1;
  ctx.strokeRect(pageX, pageY, pageWidth, pageHeight);

   
      var currentSelectedCellRowIndex=0; //当前选中的单元格所在行索引
      var currentSelectedCellIndex=0;    //当前选中的单元格所在列索引
  
      var tableColumns=0;                //表格列数
      var tableLines=0;									 //表格行数
    
      var curOnTheRightBoarder=0;         //光标在右侧边框上
      var curOnTheBottomBoarder=0;        //光标在底部边框上ing
     
      var isSelectRegionDrawing = false;    //是否开始选择操作


 
    //表格区域提示图标
  var icon = new Image();
  var iconLoaded = false; // Flag to check if the icon has loaded
  var iconVisible = false; // Flag to toggle icon visibility

  // Set your PNG icon's URL
  icon.src = 'imgs/move_icon.png'; // Replace 'your-icon.png' with the path to your icon
  icon.onload = function() {
  iconLoaded = true;
   
  };

      canvas.addEventListener('mousemove', function(e) {

       canvasOffset = $('#myCanvas').offset();

      var canvas = $('#myCanvas');
      var context = canvas.get(0).getContext('2d');
      var cursorX = e.pageX;
      var cursorY = e.pageY;

  // console.log("canvasMouse:--",cursorX,cursorY);
     
      var currentCell=null;
      var keysArray = Object.keys(jsonData);      
	    tableLines= keysArray.length;       
       startX = canvasOffset.left+tableOffsetX; //画布左边，画布的X起始点
       startY = canvasOffset.top+tableOffsetY;  //画布顶边，画布的Y起始点

      var found=0;
      var selectCellLeft=0;
      var selectCellTop=0;
      var selectCellRight=0;
      var selectCellBottom=0;

      var offset =3; 				// 光标与边线的偏移量
      var curOffsetX=offset;  
      var curOffsetY=offset;
      var curOffsetMy=offset;
  
      var inRightPosition=0;

   
      if( isIntoMenuSelection==1)//进入菜单选择状态
      {
        return;
      }
      
        for(var n=0;n<tableLines;n++)
        {
          tableTotalHeight+=jsonData[n].cells[0].height;
        }


        updateTotalWidth();// 初始化表格总长度
        updateTotalHeight();//初始化表格总高度
    


      if(isMoveTable==1)
      {
        //console.log('正在执行  表格 移动操作'); 
        tableOffsetX = cursorX-canvasOffset.left;
        tableOffsetY = cursorY-canvasOffset.top;
        whereCallDrawTable=" 移动表格重绘!";
        redraw();
        showText="正在移动表格:"+tableOffsetX+","+tableOffsetY;
        renderPosition(cursorX,cursorY,showText);
        editor_locked_cellRecord.columns=-1;
        editor_locked_cellRecord.rows=-1;




        
  
        //隐藏编辑器
        myCellCanvas.style.display='none';
    
        isInScrolling=true;
     


        return;
      }
      if(cursorX>startX-offset*2&&cursorX<startX&& cursorY>startY-offset*2&&cursorY<startY) //
       {
           isOnMoveTable=1;
           inRightPosition=1;
           whereCurIs=4;
           console.log('监测到    表格 移动区域：');
           var myCursor = "url('imgs/move_table_cursor.png') 16 16,auto";
           document.body.style.cursor = myCursor;
       }
       else
       {

        isMoveTable=0;
        isOnMoveTable=0;
       }

      var showText="";
      if( curOnBorder==1&&curOnBorderAndButtonDown==1)
      {

        //currentSelectedCellRowIndex=0; //当前选中的单元格所在行索引
        //currentSelectedCellIndex=0;    //当前选中的单元格所在列索引     

        var direct='调整列宽';
        if(whereCurIs==1)
        direct='调整行高';

        //console.log('正在调整中 '+direct+' 操作方向:'+whereCurIs+' 列数：'+tableColumns+' 光标坐标：(' + cursorX + ', ' + cursorY + ' curOnBorder:'+curOnBorder+', curOnBorderAndButtonDown:'+curOnBorderAndButtonDown+' 当前行：'+currentSelectedCellRowIndex+' 当前列:'+currentSelectedCellIndex+')');


        //处理光标在表格最右边的情况
        if(curOnTheRightBoarder==1)
        {
            var totalOffsetX=0;
            //console.log('正在调整中 宽度---------- ');
            editor_locked_cellRecord.columns=-1;
            editor_locked_cellRecord.rows=-1;
            for(var j=0;j<currentSelectedCellIndex;j++)
            {
              
              //console.log('表格最右边_调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 列号："+String(j));
                totalOffsetX+=jsonData[currentSelectedCellRowIndex].cells[j].width;//选中行下前N列的宽
        
            }
            //更新当前列单元格的宽
            for(var i=0;i<tableLines;i++)
            {
              var tempWidth=cursorX-totalOffsetX-startX;//最后一个单元格的宽，需要减去其它单元格的总宽度
              //console.log('表格最右边_调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 上单元格宽度："+String(tempWidth));
              //console.log('调整单元格大小，当前更新列上单元格高度：'+);
              if(currentSelectedCellIndex>=0) //
              {
                if(tempWidth>=15)
                jsonData[i].cells[currentSelectedCellIndex].width=tempWidth;
              }
              
          
            }

            showText="最右边单元格宽："+String(tempWidth);
            //更新表格总宽度
            updateTotalWidth(); //重新计算表格总宽度
            updateTotalHeight();//重新计算表格总高度
            lastTableTotalWidth=tableTotalWidth;//记录上一次的表格总宽度
            updateForSellMerging();
            whereCallDrawTable=" 合并单元格操作重绘!";
            redraw();
            renderPosition(cursorX,cursorY,showText);
            return ;
        }

        if(curOnTheBottomBoarder==1)//处理光标在表格最下边的情况
        {

          editor_locked_cellRecord.columns=-1;
          editor_locked_cellRecord.rows=-1;
          var totalOffsetY=0;
            for(var j=0;j<tableLines-1;j++)
            {
              
              //console.log('表格最下边_curOnTheBottomBoarder==1 调整单元格大小，当前更新列:'+j+" 列号：0 单元格高："+String(jsonData[j].cells[0].height));
                totalOffsetY+=jsonData[j].cells[0].height;//最一行之前N行高之和
        
            }

            var currentRowHeight=cursorY-startY-totalOffsetY; //最后一行的高度正在变化，所以要减去前面的行高
            showText="最下边单元格高："+String(currentRowHeight);
            //更新当最后一行单元格的高
            for(var i=0;i<tableColumns;i++)
            {
             
              //console.log('表格最下边_curOnTheBottomBoarder==1 调整单元格大小，当前更新行:'+currentSelectedCellIndex+" 上单元格宽度："+String(currentRowHeight));
              //console.log('调整单元格大小，当前更新列上单元格高度：'+);
              if(tableLines>=0)
              {
                if(curOnTheBottomBoarder==1)
                {
                  if(currentRowHeight>=15)
                  jsonData[tableLines-1].cells[i].height=currentRowHeight; //对最后一行进行更新
                }
               
              }
              
          
            }

            tableTotalHeight=0
            updateTotalHeight(); //重新计算表格总高
            updateForSellMerging();//
            whereCallDrawTable=" 重新计算表格总高!";

            redraw();
            renderPosition(cursorX,cursorY,showText);
            return ;

        }

		function getTotalOffsetYbefor() {
			var offsetY=0;
			for(var r=0;r<currentSelectedCellRowIndex;r++)
			{
			  if(r<currentSelectedCellRowIndex-1)
			  {
			    offsetY+=jsonData[r].cells[0].height;
			  }
			          
			}
			
			return offsetY;
		}

    function getTotalOffsetOfY()
    {
      var offsetY=0;
      			for(var j=0;j<currentSelectedCellRowIndex;j++)
            {
              if(j<currentSelectedCellRowIndex-1)
              {
                offsetY+=jsonData[j].cells[0].height;
              }
                      
            }
            return offsetY;
    }
		/////////////////////////////////////////////////////////////////////////////////////////////
		//调整行高:同一行所有单元格的行高都改变，bottom的Y值等于cursorY
		////////////////////////////////////////////////////////////////////////////////////////////
    if(whereCurIs==1)//调整行高:同一行所有单元格的行高都改变，bottom的Y值等于cursorY
        {
			      //计算当前单元格上面所有单元格的高度。tableLines
            var totalOffsetY=getTotalOffsetOfY();
         
            //更新当前行单元格的高，， //startY画布顶边，画布的Y起始点//totalOffsetY当前行上面所有单元格的高度
         
            var cellsHeightOfCurrentRowBefore=cursorY-startY-totalOffsetY;//当前行上面所有单元格的高度之和
            var offsetCurrentY=0;//下一行的Y启始坐标
            var upCellHeightOffset=totalOffsetY+cellsHeightOfCurrentRowBefore;
            for(var i=currentSelectedCellRowIndex;i<tableLines;i++)
            {
             
              //console.log('------------调整单元格大小，当前更新行:'+currentSelectedCellRowIndex+" 上面所有单元格高度和："+String(cellsHeightOfCurrentRowBefore));
              //console.log('调整单元格大小，当前更新列上单元格高度：'+);
              
			        if(currentSelectedCellRowIndex-1>=0)
              {   
                for(var j=0;j<tableColumns;j++)
              	{
                	if(cellsHeightOfCurrentRowBefore>=15)
                  {
                  if(currentSelectedCellRowIndex-1>=0) //被编辑的行的高度会变，大于顶行
                  {

                    //console.log('调整单元格第几行 i：'+String(i)+' 第j：'+String(j) +' 选中单元格在表的行号 currentSelectedCellRowIndex:'+String(currentSelectedCellRowIndex)+' 两者相同表示是选中行');
                    if(i==currentSelectedCellRowIndex) //调整当前行的单元格高度
                    {
                      jsonData[i-1].cells[j].height=cellsHeightOfCurrentRowBefore;
                      jsonData[i].cells[j].y=upCellHeightOffset;
                      //console.log('确认是当前表格选中行+++++++++++++++++++++++++++++++');
                    }
                    else
                    {
                      jsonData[i].cells[j].y= upCellHeightOffset;
                    }
                   
                   
                    
                    
                  }
                  else
                  {   //jsonData[i].cells[j].y+=totalOffsetY+cellsHeightOfCurrentRowBefore;
											//jsonData[i].cells[j].y=upCellHeight;
                      //offsetCurrentY=jsonData[i].cells[j].height;
                  }
                  

                  
                	}
                  
              	}	
                upCellHeightOffset+= jsonData[i].cells[currentSelectedCellIndex].height;
              }          
             
			 
            }

            
            if(cellsHeightOfCurrentRowBefore>=15)
            {
              showText="当前调整单元格高："+String(cellsHeightOfCurrentRowBefore);
            }
            else
            {
              showText="当前调整单元格高：16";
            }
						//调整后列新父亲单元格
            updateForSellMerging();
            //开始调整有合并的单元格
            
            
        }
		



		
		if(whereCurIs==2)//调整列单元格宽,左侧调整列宽，右则也相反方向调整列宽
		{
			//计算当前单元格上面所有单元格的宽度。tableLines
			var totalOffsetX=0; //调整列之前的单元格总宽
			var restOffsetX=0;  //调整列之后的单元格总宽

      var hasAnySelectCellWith=0;    //记录当前表格中，是否有当前光标下，是否有选中的单元格，如果有仅处理相关单元格，否则要处理整个表格
      var hasAnyMergeCellWith=0;     //记录当前表格中，是否有当前光标下，是否有合并的单元格，如果有要比较当前合并的单元格与当前所选的单元格是不是行号一致。如果不一致，不能调整列宽操作。
      var selectCellLineString="";   //单元格选择的行集
      var selectMergeCellString="";  //相关和合并单元格的行集
      var hadMergeCellString=0;      //标识完成合并单元格查找，用于避免重复查找
      var selectedCellOnMinRow=1000; //确定有效选择单元格最顶行行号。
      var selectedCeloOnMaxRow=0;    //确定有效选择单元格最底部行号。
      var whereIsMergecel=0;         //0表示没有发现有合并单元格在当前光标下，1表示有合并单元格在当前光标下（同行），2表示左则有
      var mergeCellOnMinRow=1000;    //合并单元格最顶行号
      var mergeCellOnMaxRow=0;       //合并单元格最底部行号
       
      var hadShereLine=0;            //判断选择区 和  合并单元格有e交集


      //为了判断所在的表格中，是否有当前光标下，是否有选中的单元格，如果有仅处理相关单元格，否则要处理整个表格
        for(var i=0;i<tableLines;i++)  //从第一行开始查找
        {
            if(currentSelectedCellIndex<=0)
            return;
            //查找当光标位置，左是否有选的单元格
            if(jsonData[i].cells[currentSelectedCellIndex-1].selected==1||jsonData[i].cells[currentSelectedCellIndex].selected==1)
            {

              //冒泡最大最小行号
              if(i<selectedCellOnMinRow)
              selectedCellOnMinRow=i;
              if(i>selectedCeloOnMaxRow)
              selectedCeloOnMaxRow=i;


              hasAnySelectCellWith++;
             // console.log("A4 找到选中的单元格，line:"+i+" col:"+currentSelectedCellIndex);
             
              if(selectCellLineString==="")
                selectCellLineString=i;
              else
                selectCellLineString= selectCellLineString+","+i;
            }

            if(jsonData[i].cells[currentSelectedCellIndex-1].parentRow>=0&&jsonData[i].cells[currentSelectedCellIndex].selected==1) //左则有合并单元格,行数大于0,并与选中行同行
            {
              var parentCellRowIndex=jsonData[i].cells[currentSelectedCellIndex-1].parentRow;
              var parentCellColIndex=jsonData[i].cells[currentSelectedCellIndex-1].parentCol;
              var parentCell=  jsonData[parentCellRowIndex].cells[parentCellColIndex];

              //console.log("A4 有合并的单元格:"+i+" col:"+currentSelectedCellIndex);

                  if(hadMergeCellString==0)
                  {
                      for(var m=parentCellRowIndex;m<=parentCell.rowspan;m++)
                      {
                        if(selectMergeCellString==="")
                        {
                          selectMergeCellString=m;
                        }
                        else
                        {
                          selectMergeCellString=selectMergeCellString+","+m;
                        }

                        //console.log("A4 找到被合并相邻单元格行集，line:"+i+" col:"+currentSelectedCellIndex+" 集合有："+selectMergeCellString);
                        hasAnyMergeCellWith++;
                        whereIsMergecel=1;

                        if(m< mergeCellOnMinRow)
                        mergeCellOnMinRow=m;    //合并单元格最顶行号

                        if(m>mergeCellOnMaxRow)
                        mergeCellOnMaxRow=m;       //合并单元格最底部行号


                      }
                      hadMergeCellString=1;

                  }
               
            }

            //另一种可能：合并单元格与当前选择的单元格同行，且当前选择的单元格是合并单元格的子单元格
            if(hadMergeCellString==0)
            {
                //console.log("A4 if(rowspan>0){"+jsonData[i].cells[currentSelectedCellIndex-1].rowspan+"}&& selected={"+jsonData[i].cells[currentSelectedCellIndex].selected+"}");
                if(jsonData[i].cells[currentSelectedCellIndex-1].rowspan>0&&jsonData[i].cells[currentSelectedCellIndex].selected==1) //左则有合并单元格,行数大于0,并与选中行同行
                {

                 
                  var parentCell=  jsonData[i].cells[currentSelectedCellIndex-1];//定位到合并单元格的主单元格

                  //console.log("A4 有合并的单元格:"+i+" col:"+(currentSelectedCellIndex-1)+" 跨行数： parentCell.rowspan="+parentCell.rowspan);

                 
                      for(var m=i;m<=parentCell.rowspan;m++)
                      {
                        if(selectMergeCellString==="")
                        {
                          selectMergeCellString=m;
                        }
                        else
                        {
                          selectMergeCellString=selectMergeCellString+","+m;
                        }

                        hasAnyMergeCellWith++;
                        if(m<= mergeCellOnMinRow)
                        mergeCellOnMinRow=m;    //合并单元格最顶行号

                        if(m>=mergeCellOnMaxRow)
                        mergeCellOnMaxRow=m;       //合并单元格最底部行号

                        //console.log("A4 找到被合并相邻单元格行集，line:"+i+" col:"+currentSelectedCellIndex+" 集合有："+selectMergeCellString);

                      }
                      hadMergeCellString=1;
                      whereIsMergecel=2;

                 

                 // console.log("A4 找到被合并相邻同行单元格行集，line:"+i+" col:"+currentSelectedCellIndex);

                  
                }

            }
            

          
      
        
      }

      // var selectedCellOnMinRow=1000; //确定有效选择单元格最顶行行号。
      // var selectedCeloOnMaxRow=0;    //确定有效选择单元格最底部行号。
      //console.log("A4 有效行号顶行："+selectedCellOnMinRow+" 底部行号："+selectedCeloOnMaxRow+ " 1合并单元在左侧 2在同行："+ whereIsMergecel);
     // console.log("A4 合并行号顶行："+mergeCellOnMinRow+" 底部行号："+mergeCellOnMaxRow);


    //当mergeCells区域在上边，selectedCells在下边。求是否有交集：
    var hasShearLineA=0;
    //M代表mergeCells, S代表 selectedCells;

    //判断mergeCells与selectedCells的方位关系(M上S下)
    if(selectedCellOnMinRow>mergeCellOnMinRow)
    {
      
      if(selectedCellOnMinRow-mergeCellOnMaxRow>0)
      hasShearLineA=0;
      else
      hasShearLineA=1;


    }
    //console.log("A4 (M上S下) 区域有交集:"+hasShearLineA);


    //当selectedCells 区域在上边，mergeCells在下边。求是否有交集：
    var hasShareLineB=0;
       //判断mergeCells与selectedCells的方位关系(S上M下)
    if(mergeCellOnMinRow >selectedCellOnMinRow)
    {
      

      if(mergeCellOnMinRow-selectedCeloOnMaxRow>0)
      hasShareLineB=0;
      else
      hasShareLineB=1;
    }
    //console.log("A4 (S上M下) 区域有交集:"+hasShareLineB);

  

    if(hasShearLineA==1||hasShareLineB==1)
     hadShereLine=1;
     //console.log("A4 selectedCells在mergeCells区域有交集:"+hadShereLine);
     //selectedCells在mergeCells区域区间
    if(mergeCellOnMinRow<selectedCellOnMinRow&&mergeCellOnMinRow<selectedCeloOnMaxRow&&mergeCellOnMaxRow>selectedCellOnMinRow&&mergeCellOnMaxRow>selectedCellOnMinRow)
    hadShereLine=1;

    //console.log("A4 A selectedCells在mergeCells区域有交集:"+hadShereLine);
     if((selectedCellOnMinRow-selectedCeloOnMaxRow>0)&&(selectedCeloOnMaxRow-selectedCeloOnMaxRow>0))
     {
      hadShereLine=0;
     }

     //console.log("A4 B selectedCells在mergeCells区域有交集:"+hadShereLine);
     // console.log("A4 找到选中的单元格数，hadShereLine:"+hadShereLine+" hasAnySelectCellWith:"+hasAnySelectCellWith+"  hasAnyMergeCellWith:"+hasAnyMergeCellWith+  " 选择的行集："+selectCellLineString+"  合并格行集："+selectMergeCellString+" 表格总行数："+tableLines);

      if(whereIsMergecel==2)//同行有合并的单元，判断
      {
        if(selectCellLineString!==selectMergeCellString) //断定被选中的单元格与合并单元格不是在相同的行号上，则不能调整列宽
        {
          return;
        }

      }
      //当选择表格有单元格在调整区域，同时周边有被合并单元格的集合,两个区域有交集
      if(hasAnySelectCellWith>0&&hasAnyMergeCellWith>0&&hadShereLine==1)
      {
        if(selectCellLineString!==selectMergeCellString) //断定被选中的单元格与合并单元格不是在相同的行号上，则不能调整列宽
        {
          return;
        }
        
      }
      else
      {
        if(hasAnyMergeCellWith==0)
        {
         // console.log("A4 在周边没有找到合并单元格");
        }
      }
      


      //当前一个单元格宽度变化时，后一个单元格的宽度变化，X坐标也做相应的变化
      //X坐标变化量=当前一个单元格宽度+totalOffsetX
     
      //记信当前前后单元格变化前的值，用于后面辅助计算，单元格移动方向 
      var currentLeftCellWidth; //当前单元格左边单元格的宽度
      var currentRightCellWidth;//当前单元格右边单元格的宽度
      var moveToLeft=1;//0向左移动，1向右移动
      //记录当前单元格左边和右边单元格的宽度
      currentLeftCellWidth=jsonData[currentSelectedCellRowIndex].cells[currentSelectedCellIndex-1].width; //左边表格
      currentRightCellWidth=jsonData[currentSelectedCellRowIndex].cells[currentSelectedCellIndex].width; //右边表格

			for(var j=0;j<currentSelectedCellIndex-1;j++)
			{
				
        //console.log('调整单元格大小==》，当前更新列:'+currentSelectedCellRowIndex+" 列号："+String(j));
        if(j<tableColumns)
				totalOffsetX+=jsonData[currentSelectedCellRowIndex].cells[j].width;//选中行下前N列的宽
	
			} 

      for(var j=currentSelectedCellIndex+1;j<tableColumns;j++) 
      {
       // console.log('j:'+String(j)+'行先:'+String(currentSelectedCellRowIndex+1));
        if(currentSelectedCellRowIndex+1<=tableLines)
          restOffsetX+=jsonData[0].cells[j].width;//选中行下后N列的宽
          
        
       
      }
      
        var tempWidth=cursorX-startX-totalOffsetX; //计算出当前光标左列的宽度，
        var afterCellWidth=jsonData[0].cells[currentSelectedCellIndex].width;//光标右则的单元格更新后的高，计算值；
       

        //如果光标在最后一列，最后一是列的宽度小于15后，向左拉时，表格最右边保持不变
        if(afterCellWidth>=15)
        {
          afterCellWidth=lastTableTotalWidth-totalOffsetX-cursorX+startX;
          
        }

     
        
        if(currentSelectedCellIndex>=0&&currentSelectedCellIndex<tableColumns)
        {
            
						//console.log('选中列：'+currentSelectedCellIndex+'当前表格总宽度：'+String(tableTotalWidth)+' totalOffsetX：'+String(totalOffsetX+tempWidth)+' restWidth:'+String(restOffsetX)+' 上一次表格总宽度:'+String(lastTableTotalWidth)+'calculate total:'+String(currentLeftCellWidth+currentRightCellWidth+restOffsetX+totalOffsetX));

            //如果宽度变小，则需要调整右边表格的宽度
            var subWidth= g_selectedCellWidth_L-tempWidth;//老的宽度-变化后的宽度

            if(tempWidth>0)//左单元格比之前变小，右则的单元格宽度需要变宽
            {
              if((totalOffsetX+tempWidth+restOffsetX)<lastTableTotalWidth-15)
              {
                if((jsonData[0].cells[currentSelectedCellIndex].width-subWidth)>=15)//后面的单元格宽度足够
              	{
                 afterCellWidth=currentRightCellWidth+subWidth;
                 
              	}  		 
              }
              else
              {
                return;
              }
                       
             
            }
            else//变窄
            {
              afterCellWidth=currentRightCellWidth-subWidth;
            }

        }
         

      //更新当前列单元格的宽
        if(lastTableTotalWidth-totalOffsetX+tempWidth-restOffsetX<0)//判读光标后一列单元格小于16
        {
          
          	
              afterCellWidth=16;
              tempWidth=lastTableTotalWidth-totalOffsetX-afterCellWidth-restOffsetX;        
           
          // console.log('越过总长度:'+String(totalOffsetX+tempWidth+afterCellWidth)+' afterCellWidth:'+String(afterCellWidth)+ ' TableTotalWidth:'+String(tableTotalWidth)+' tempCounterTotalOffsetX:'+String(tempCounterTotalOffsetX));
          // curOnBorder=0;
          //  return;
        }
        //当最新表宽大于旧表宽时，需要调整列宽
       
        if((totalOffsetX+afterCellWidth+restOffsetX+tempWidth)<lastTableTotalWidth)
        {
          if(tempWidth<=15)
          {
             tempWidth=15;
          }
         
          afterCellWidth=lastTableTotalWidth-totalOffsetX-tempWidth-restOffsetX;
          //console.log('总长度受影响越:'+String(totalOffsetX+afterCellWidth+restOffsetX+tempWidth)+' afterCellWidth:'+String(afterCellWidth)+ ' TableTotalWidth:'+String(tableTotalWidth)+' tempCounterTotalOffsetX:'+String(tempCounterTotalOffsetX));
        
        }

        //修正总表宽度大于最新表宽度时，需要调整列宽
        if((totalOffsetX+tempWidth+afterCellWidth+restOffsetX)>lastTableTotalWidth)
        {
          afterCellWidth=lastTableTotalWidth-totalOffsetX-tempWidth-restOffsetX;
         
          //console.log('总长度受影响大越:'+String(totalOffsetX+afterCellWidth+restOffsetX+tempWidth)+' afterCellWidth:'+String(afterCellWidth)+ ' TableTotalWidth:'+String(tableTotalWidth)+' tempCounterTotalOffsetX:'+String(tempCounterTotalOffsetX));
      
        }
      
        showText="左单元格宽:"+String(tempWidth)+" 右单元格宽:"+String(afterCellWidth);
     
        var tempCounterTotalOffsetX=0; //调整列之前的单元格总宽
        for( var j=0;j<tableColumns;j++)
        {
          tempCounterTotalOffsetX+=jsonData[currentSelectedCellRowIndex].cells[j].width;
          
        }
        // if(tempCounterTotalOffsetX>lastTableTotalWidth)
        // {
        //   console.log('===========调整后大于:'+String(totalOffsetX+afterCellWidth+restOffsetX+tempWidth))
        //   return;
        // }

        //判断单元格移动方向；
       

        if((g_selectedCellWidth_L-tempWidth)>0)//左单元格变宽了，向右移动了
        {
          moveToLeft=1;
        }
        else
        {
          moveToLeft=0;
        }

        var currentBeforCellOffset=totalOffsetX;//右则单元格X坐标
		    for(var i=0;i<tableLines;i++) //当一列宽变化时，所有行的列该列宽都要变化
		    {   
          
		      //console.log('调整单元格大小，当前更新列:'+g_selectedColumn+" 上单元格宽度："+String(tempWidth));   
          
            if(currentSelectedCellIndex-1>=0&currentSelectedCellIndex<tableColumns) //有效列下标限定
            {
          
              //当前更左边单元格调整后，后边的单元格的宽度发生变化，而后边单元格的x坐标等于左边单元格宽+左边所有单元格偏移之和
              if(tempWidth>=15)
              {
               // if(g_selectedColumn==j)
                {

                  // jsonData[i].cells[j-1].width=tempWidth; //左单元格宽设定
                  // currentBeforCellOffset+=tempWidth;
                 

                  var tempWidthAfter=0;
                  
                      if((jsonData[i].cells[currentSelectedCellIndex-1].selected==1||jsonData[i].cells[currentSelectedCellIndex].selected==1)||hadShereLine==1) //当有交集，，要求选择内为有
                      {

                      
                      if(moveToLeft==1)
                      {
                        //左移之后，右单元格宽度变小，计算出变化量 
                        //g_selectedColumn=cellIndex;  //全选中的列
                        //g_selectedRow=rowIndex;     //全选中的行
                        var W_L=g_selectedCellWidth_L;
                        var W_R=g_selectedCellWidth_R;
                        
                        var W_L_1=tempWidth;
                        var W_sub=W_L-W_L_1;

                        var W_R_1_x=W_L-W_sub+totalOffsetX;
                        var W_R_1_W=W_R+W_sub;
                        

                        tempWidthAfter=W_R_1_W;
                        //右单元格 X坐标与W宽变动

                        if(hasAnySelectCellWith==0) //所在列没有选中项
                        {
                          jsonData[i].cells[g_selectedColumn].x=W_R_1_x;
                          jsonData[i].cells[g_selectedColumn].width=W_R_1_W;

                          jsonData[i].cells[g_selectedColumn-1].width=W_L_1; 

                        }
                        else
                        {
                          //只对选择的单元格进行更新宽度与起始坐标。
                          if(jsonData[i].cells[g_selectedColumn].selected==true||jsonData[i].cells[g_selectedColumn-1].selected==true)
                          {
                            jsonData[i].cells[g_selectedColumn].x=W_R_1_x;
                            jsonData[i].cells[g_selectedColumn].width=W_R_1_W;

                            jsonData[i].cells[g_selectedColumn-1].width=W_L_1; 

                          }
                          
                        }


                        //console.log('首列 左移-----【小】【大】 左格宽变化量：'+String(W_sub)+' L_旧宽 ：'+W_L+' 变小 L_现宽：'+W_L_1+ ' R_旧格宽：'+W_R+' 变大 现右格宽：'+String(W_R_1_W));
                        //console.log('首列 两单元格移动前宽和：'+String(g_selectedCellWidth_L+g_selectedCellWidth_R)+' 移动后之和'+String(tempWidth+tempWidthAfter));           
                       // console.log('首列 左移 g_selectedColumn：'+String(g_selectedColumn)+ ' g_selectedRow:'+String(g_selectedRow)+' Wl:'+String(g_selectedCellWidth_L)+' Wr:' +String(g_selectedCellWidth_R));



                        // if(afterCellWidth>=15)
                        // {
                        //   console.log('最后一个单元格列宽大于15：'+String(afterCellWidth));
                        //       jsonData[i].cells[j].width=afterCellWidth;
                        // }        
                        // else
                        // {  //小于或等于15
                        //   console.log('最后一个单元格列宽 小于15：'+String(afterCellWidth));
                        //   var myWidth=lastTableTotalWidth-totalOffsetX-currentLeftCellWidth-restOffsetX;
                        //   jsonData[i].cells[j].width=myWidth;
                        // }
                      }
                    
                      else  //光标右移：单元格右移，左单元格宽度变大，右单元格宽度后小
                      {
                     
                        var W_L=g_selectedCellWidth_L;
                        var W_R=g_selectedCellWidth_R;
                        
                        var W_L_1=tempWidth;
                        var W_sub=W_L_1-W_L;

                        var W_R_1_x=W_L+W_sub+totalOffsetX;
                        var W_R_1_W=W_R-W_sub;
                        

                        tempWidthAfter=W_R_1_W;
                        //右单元格 X坐标与W宽变动
                        jsonData[i].cells[g_selectedColumn].x=W_R_1_x;
                        jsonData[i].cells[g_selectedColumn].width=W_R_1_W;

                        jsonData[i].cells[g_selectedColumn-1].width=W_L_1; 

                        //console.log('首列 左移-----【小】【大】 左格宽变化量：'+String(W_sub)+' L_旧宽 ：'+W_L+' 变小 L_现宽：'+W_L_1+ ' R_旧格宽：'+W_R+' 变大 现右格宽：'+String(W_R_1_W));
                        //console.log('首列 两单元格移动前宽和：'+String(g_selectedCellWidth_L+g_selectedCellWidth_R)+' 移动后之和'+String(tempWidth+tempWidthAfter));           
                       // console.log('首列 左移 g_selectedColumn：'+String(g_selectedColumn)+ ' g_selectedRow:'+String(g_selectedRow)+' Wl:'+String(g_selectedCellWidth_L)+' Wr:' +String(g_selectedCellWidth_R));

                        
                      }
                      
                     }
                 // jsonData[i].cells[j].width=tempWidthAfter;//右边单元格的宽度变化
                 
                }
                

              }

            }
     
		      
			 
		    }
      	//调整后列新父亲单元格
        updateForSellMerging();
		}
		var floatOnBoard=0;
		//isSelecting = false;
		    currentSelection = [];
        updateTotalHeight();// 重新计算表格总高度
        redraw();
        renderPosition(cursorX,cursorY,showText);
        return;
      }
      
     // $('#cursorCoordinates').text('光标坐标监控全局：(' + cursorX + ', ' + cursorY +')');

 

      //表格选中监测=========================================================================================================
      //遍历行
       cellStartX = canvasOffset.left+tableOffsetX;
       cellStartY = canvasOffset.top+tableOffsetY;
      for (var rowIndex = 0; rowIndex < tableLines; rowIndex++) {
      
        var row = jsonData[rowIndex].cells; //表格行单元格数组
         //遍历行中的每个单元格       
         //遍历列 
         if(row.length>0)
         tableColumns=row.length;
           //console.log('=====当前 遍历列:(' + rowIndex +')'+'光标坐标：(' + cursorX + ', ' + cursorY +') 表格共有列数:'+String(tableRows) );
        
		  //遍历每一列，是不是在选中范围内
          for (var cellIndex = 0; cellIndex < row.length; cellIndex++) { 
          // 获取单元格的位置信息
          console.log();
          var cell = row[cellIndex];//当前行第N个的单元格
          //startX表格起始点x坐标
          //startY表格起始点y坐标
         
          //console.log('rowIndex:(' + rowIndex +' cellIndex:'+cellIndex+')  单元格位置：cell.x:(' + String(cellStartX) +' cell.y:'+String(cellStartY)+')'+' 光标坐标：(' + cursorX + ','+ cursorY + ')');
          //console.log('rowIndex:(' + rowIndex +' cellIndex:'+cellIndex+')  单元格位置：cell.x:(' + startX +' cell.y:'+startY+')'+' 光标坐标：(' + cursorX + ', ' + cursorY + ')');
          if (cursorX >= cellStartX && cursorX <= cellStartX + cell.width &&
              cursorY >= cellStartY && cursorY <= cellStartY + cell.height) {
                
         
           // console.log('=====光标在所在 行:(' + rowIndex +' 列:'+cellIndex+')');

       			if(isSelecting==true)
            {
              cursorIsInSideOfCell=1;
            }
            else
            {
              if((cellStartX+offset)<cursorX&& //光标X在左则偏移右边
              cursorX<(cellStartX+cell.width-offset)&&//光标X在右则偏移左边
              (cellStartY+offset)<cursorY&&//光标Y在上则偏移下边
              cursorY<(cellStartY+cell.height-offset))//光标Y在下则偏移上边
              {
                cursorIsInSideOfCell=1;
               
                //console.log('光标在单元格内心==============');
              }
              else
							{
                cursorIsInSideOfCell=0;
               // console.log('光标不在单元格内心==============');

               if(whereCurIs!=1)
               {
                  g_selectedColumn=cellIndex;  //全选中的列
                  g_selectedRow=rowIndex;     //全选中的行

                  if(g_selectedColumn>0)
                  {
                    g_selectedCellWidth_L=jsonData[g_selectedRow].cells[g_selectedColumn-1].width;
                    g_selectedCellWidth_R=jsonData[g_selectedRow].cells[g_selectedColumn].width;

                  }
                 
               }
              
              }



         	
            }
           

            selectCellLeft=cellStartX;
            selectCellTop=cellStartY;
            selectCellRight=cellStartX+cell.width;
            selectCellBottom=cellStartY+cell.height;
            document.body.style.cursor = 'default';
            currentCell = cell;
            found=1;
            
            if(cellIndex==tableLines)//光标在最后一行
            {
              //console.log('光标在最后一列 =rowIndex:(' + rowIndex +' cellIndex:'+cellIndex+')');
            }
            if(curOnBorderAndButtonDown==0) //只有在结构上没有按下按钮时，才进行选中
            {
              currentSelectedCellRowIndex=rowIndex;
              currentSelectedCellIndex=cellIndex;
            }
           
            break;
          }
          cellStartX += cell.width;
        }
        if(found==1 )
        break;
        cellStartX = startX;
        cellStartY += row[0].height;
      }
     
      if(found==1) //当光标在表格上时，显示左上角的移动表格提示图标
      {
        //if (iconVisible) {
         // Draw the icon
         ctx.drawImage(icon, tableOffsetX - icon.width, tableOffsetY - icon.height);
        // console.log('开始画图标===============)');
        //}
      }
      else
      {
        //console.log('清除开始画图标===============)');
        isSelecting = false;
        currentSelection = [];
        selectedCells = selectedCells.concat(currentSelection);
        
     
        cursorIsInSideOfCell=0;
       
    
       // redraw();
      }

         //表格选中功能
         if (isSelectingForCell) {
         var canvas = $('#myCanvas');
         var rect = canvas.get(0).getBoundingClientRect();
       
         var x = e.clientX - rect.left;
         var y = e.clientY - rect.top;
   
        x=cursorX-canvasOffset.left-tableOffsetX;
        y=cursorY-canvasOffset.top-tableOffsetY;
     
        //console.log('==========表格选中设置x ：'+String(x)+" y: "+String(y)+' whereCurIs:'+String(whereCurIs));
				//redraw();

     
        selectionEndX =x;
        selectionEndY =y;
        // Select cells within the dragging area
        jsonData.forEach(function(rowData, rowIndex) {
          rowData.cells.forEach(function(cell, cellIndex) {
            cell.selected = (
              cell.x < Math.max(selectionStartX, selectionEndX) &&
              cell.x + cell.width > Math.min(selectionStartX, selectionEndX) &&
              cell.y < Math.max(selectionStartY, selectionEndY) &&
              cell.y + cell.height > Math.min(selectionStartY, selectionEndY)
            );
          });
        });
        

        whereCallDrawTable=" 表格选中功能";//在哪调用了drawTable
        drawTable();
        return;
      }

        //光标表格在最右边。OK 
        if((tableTotalWidth-offset+startX)<cursorX&&cursorX<(tableTotalWidth+offset+startX)&&cursorY>startY&&cursorY<(tableTotalHeight+startY)&&cursorY>startY)
         {
          //光标在表格的最右边上
           curOnTheRightBoarder=1;
           whereCurIs=2;
           var myCursor = "url('imgs/l_r_cursor.png') 8 8,auto";
           document.body.style.cursor = myCursor;
           //console.log('监测到 光标在表格最右边边边------------------totalWidth:'+tableTotalWidth+' cursorX:'+cursorX+' offset:'+offset);
            return;
        
         }
         else
         {
           curOnTheRightBoarder=0;

         }


         //curOnTheBottomBoarder
         if((tableTotalHeight-curOffsetY+startY)<cursorY&&cursorY<(tableTotalHeight+curOffsetY+startY))
         {
          //光标在表格的最下边上
           curOnTheBottomBoarder=1;
           whereCurIs=4;
           var myCursor = "url('imgs/u_d_cursor.png') 8 8,auto";
            document.body.style.cursor = myCursor;
            //console.log('监测到 光标在表格最下边边边------------------totalWidth:'+tableTotalWidth+' cursorX:'+cursorX+' offset:'+offset);
            return;
         }else
         {
           curOnTheBottomBoarder=0;
         }

        //光标在单元格上方，立即更新光标为上下双箭头,调整高度的情形
       if(cursorX>startX&&cursorX<(tableTotalWidth+startX)&&cursorY>(selectCellTop-offset)&&cursorY<(selectCellTop+offset))
       {
           
            if(currentSelectedCellRowIndex==0)
            {
              //光标在第一行的上边，变光标为单向下箭头
              var myCursor = "url('imgs/down_cursor.png') 8 8,auto";
              document.body.style.cursor = myCursor;
              inRightPosition=1;
              whereCurIs=3;
              //console.log('监测到 光标在单元格首行顶线上-------------------');

            }
            else
            {
              //console.log('监测到  光标在单元格的上边线上 当前行：'+currentSelectedCellRowIndex+' 当前列:'+currentSelectedCellIndex);
              //console.log('监测到  光标在单元格的上边线上 startX:',startX," tableTotalWidth:",tableTotalWidth," selectCellTop:",selectCellTop);
              var myCursor = "url('imgs/u_d_cursor.png') 8 8,auto";
              document.body.style.cursor = myCursor;//上下双箭头
              //document.body.style.cursor = 'ns-resize';//上下双箭头
              inRightPosition=1;
              whereCurIs=1;

            }

            floatOnBoard=1;
           
       }
 
   

     
        //光标在左侧边，立即更新光标为左右双箭,调节宽度的情形
       if(cursorX>(selectCellLeft-offset*2)&&cursorX<(selectCellLeft+offset)&&cursorY>startY&&cursorY<(tableTotalHeight+startY))      
       {

       // console.log('监测到 光标在单元格首行最左边线上：-------------------：：：'+currentSelectedCellIndex);
            if(currentSelectedCellIndex==0)//光标在第一列的左边
            {
               //光标在第一行的上边，变光标为单向下箭头
               var myCursor = "url('imgs/right_cursor.png')8 8, auto";
              document.body.style.cursor = myCursor;
             // console.log('光标在单元格首行最左边线上-------------------');
           
            }
            else
            {
              //document.body.style.cursor = 'ew-resize';//左右双箭头
             // console.log('光标在单元格左边线上-------------------');
             var myCursor = "url('imgs/l_r_cursor.png') 8 8,auto";
              document.body.style.cursor = myCursor;//左右双箭头
            }
           
           
            floatOnBoard=1;
            inRightPosition=1;//在正确的位置上
            whereCurIs=2;
       }
       

       if(inRightPosition==0)
        {
          document.body.style.cursor = 'default';
        }
       else
        {  
          if(cursorIsInSideOfCell==1)//光标在单元格内心
          {
            floatOnBoard=0;//光标不在边线上
            whereCurIs=5;//光标在单元格内心

            var canvasOffset = $('#myCanvas').offset(); 
            cellStartX = canvasOffset.left+tableOffsetX;
            cellStartY = canvasOffset.top+tableOffsetY;

                var cell_X = cellStartX + cell.x;
                var cell_Y = cellStartY + cell.y;  		


                lastSizeOfCellCanvas.left=(cell_X)+"px";
                lastSizeOfCellCanvas.top=(cell_Y)+"px";
                lastSizeOfCellCanvas.width=cell.width;    
								lastSizeOfCellCanvas.height= cell.height;
                textData=cell;
                lastTextData=cell;
                lastTextData.text=cell.content;
          }
          else
          {
          
          }
          

          if(floatOnBoard==1)
          {
           // console.log('在表格边上悬浮 1,光标在单元格的上边线上, 2光标在左侧边; 3光标在第一行的上边; 4，在最下边单元格；5光标在单元格内部 ：'+ String(whereCurIs));
            curOnBorder=1;
          }
          else
          {
            curOnBorder=0;
           // console.log('不在表格边上悬浮  1,光标在单元格的上边线上, 2光标在左侧边; 3光标在第一行的上边; 4，在最下边单元格； 5光标在单元格内部  ：'+ String(whereCurIs));
          }
         
        }

      if(curOnBorderAndButtonDown==1)
      {
       
        if(whereCurIs==1)//光标在单元格上方，调节高度
        { 
          //console.log('调整单元格大小，当前所在行:'+currentSelectedCellRowIndex+" 表格列数： "+tableRows);
          if(currentSelectedCellRowIndex!=0)//第一行不处理
          {

            //更新当前行单元格的高度
            for(var i=0;i<tableRows;i++)
            {
              //console.log('调整单元格大小，当前更新列:'+currentSelectedCellRowIndex+" 上单元格高度："+cursorY-canvasOffset);
              //jsonData[currentSelectedCellRowIndex].cells[i].height=cursorY-selectCellTop-canvasOffset;
            }
            
          }

        }



      }
      
   


      
    });

    // 双击事件处理器
  canvas.addEventListener('dblclick', function(event) {
   allowEditCell=true;
   
  });

  /*===================================================================
  OnMouseUp 处理鼠标释放事件
  =====================================================================*/

    canvas.addEventListener('mouseup', function(e) {

      if (e.which === 1) 
      {
          e.preventDefault();
      }

      
    if (isSelectingForCell) {
       
      isSelectingForCell=false;
     

              //查询是否有需要合并的单元格,如果有就弹出菜单
        var hasMoreThanOneCellSelected = 0;
        var canSplitCells = 0;
        var canMergeCells = 0;
        var havOneParent=1;
        var parentX=0;
        var parentY=0;
        //如果在选择的单元格中，只有一个格
         jsonData.forEach(function(rowData, rowIndex) {
         rowData.cells.forEach(function(cell, cellIndex) {   
           
             if( cell.selected ==true)
             {
             
              hasMoreThanOneCellSelected++;
             
              canMergeCells++;

              if(cell.rowspan>0||cell.colspan>0)
              canSplitCells++;
                 
             }
             
        });
      });

      if(canSplitCells>0)
      {
        highlightButton('splitCells', 1);
      }
      else
      {
        highlightButton('splitCells', 0);
      }

      if(canMergeCells>1)
      {
        highlightButton('MergeCells', 1);
      }
      else
      {
        highlightButton('MergeCells', 0);
      }
     
    
      
      //console.log('表格选择鼠标左键被释放。splitCells:'+canSplitCells+' MergeCells:'+canMergeCells);
      
     return;
     ///////////////////////合并完成
  
      }

    if(curOnTheRightBoarder==1)//当调节单元格右边框时，释放。
    {
      
      curOnTheRightBoarder=0;  
      curOnTheBottomBoarder=0;
      curOnBorder=0;//释放单元格边线
      curOnBorderAndButtonDown=0;
	 
     // console.log('表格最右侧单元格鼠标左键被释放。');
      return;
    }
    if(isMoveTable==1)
    {
      isMoveTable=false;
      isOnMoveTable=false
      curOnTheRightBoarder=0;  
      curOnTheBottomBoarder=0;
      curOnBorder=0;//释放单元格边线
      curOnBorderAndButtonDown=0;
	  saveState();
      //console.log('表格移动状态鼠标左键被释放。');
    }

    if(curOnTheBottomBoarder==1)
    {
      curOnTheBottomBoarder=0;
      curOnTheRightBoarder=0;  
      curOnBorder=0;//释放单元格边线
      curOnBorderAndButtonDown=0;
      //console.log('表格最下行鼠标左键被释放。');
	  saveState();
      return;  
    }

	 if( curOnBorder==1&&curOnBorderAndButtonDown==1)
	 { curOnBorderAndButtonDown=0;//释放单元格调整按钮
     curOnBorder=0;//释放单元格边线
     document.body.style.cursor ='default';//恢复默认光标
    // console.log('表格调整键被释放。');
	 saveState();
	   return;//在调整时，不做选择操作。
		 
	 }
   isSelectRegionDrawing = false;    //是否开始选择操作
  
      
    });


  /*===================================================================
      OnMouseDown 处理鼠标左键按下事件
  =====================================================================*/
    canvas.addEventListener('mousedown', function(e) {
		
     		var canvas = $('#myCanvas');
     		var context = canvas.get(0).getContext('2d');
     		var rect = canvas.get(0).getBoundingClientRect();
     		 canvasOffset = canvas.offset();
	
         var cursorX = e.pageX;
         var cursorY = e.pageY;

      	var x = e.clientX - rect.left;
      	var y = e.clientY - rect.top;
          x=cursorX-canvasOffset.left-tableOffsetX;
          y=cursorY-canvasOffset.top-tableOffsetY;
        //selectionStart = getCellFromCoords(x, y);//获取开始单元格
        
      if (cursorIsInSideOfCell==1) {
        isIntoMenuSelection=0;//进入菜单选择状态
        //hideMenu();
        loadAtFirstTime=false;
        //console.log('鼠标左键被按下 获取开始单元格 进入选择状态:-----------------:'+selectionStart+' x="'+String(x)+'" y="'+String(y)+'"');  
        
        isSelectingForCell = true;  
        selectionStartX = x;
        selectionStartY = y;
        myCanvasInitY=myCellCanvas.style.top;

          // jsonData[editor_locked_cellRecord.rows].cells[editor_locked_cellRecord.columns].cells_selectionEnd=0;
          // jsonData[editor_locked_cellRecord.rows].cells[editor_locked_cellRecord.columns].cells_selectionStart=0;

        jsonData.forEach(function(rowData, rowIndex) {
        rowData.cells.forEach(function(cell, cellIndex) {           
              cell.selected = false;
              cell.cells_selectionStart=0;
              cell.cells_selectSecond=0;
              cell.cells_selectionEnd=0;
        });
       
       // redraw();
      });



        const cell = getCellByCoords(selectionStartX, selectionStartY);

        if (cell) {
          cell.selected = !cell.selected;
          redraw();
        }
       
        return;
      }


 

      if(isOnMoveTable==1)//光标在表格左上，，置可移动表格
      {
          curOnBorder=1;
          var myCursor = "url('imgs/move_table_cursor.png') 16 16,auto";
          document.body.style.cursor = myCursor;
          curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下  
          isMoveTable=1;  //置表格可移动
          //console.log('表格左上角 鼠标左键被按下。');
          return;
      }

     //光标在表格的最右边上
     if(curOnTheRightBoarder==1)
     {
          var myCursor = "url('imgs/l_r_cursor.png') 8 8,auto";
          document.body.style.cursor = myCursor;
          curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下  
          curOnBorder=1;
         // console.log('表格最右边上鼠标左键被按下。');
          return;
     }

         //光标在表格的最下边上
    if(curOnTheBottomBoarder==1)
     {
          var myCursor = "url('imgs/u_d_cursor.png') 8 8,auto";
          document.body.style.cursor = myCursor;
          curOnTheBottomBoarder=1; 
          curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下
          curOnBorder=1; 
          console.log('表格最下边上鼠标左键被按下。');
          return;
     }
          
            
  
    if( curOnBorder==1)         //光标在边框上
    {
          console.log('光标在边框上-鼠标左键被按下。');
          curOnBorderAndButtonDown=1; //光标在边框上且左键按钮被按下  
          return;
    }
    
     isSelectRegionDrawing = true;    //是否开始选择操作
  
     var canvas = $('#myCanvas');
     var context = canvas.get(0).getContext('2d');
     var rect = canvas.get(0).getBoundingClientRect();
    
       
        var x = e.clientX - rect.left;
        var y = e.clientY - rect.top;
        x=x-canvasOffset.left-tableOffsetX;
        y=y-canvasOffset.top-tableOffsetY;

        selectionStart = getCellFromCoords(x, y);
        if (selectionStart) {
          isSelecting = true;
          selectedCells = []; // Clear previous selection, if we want to support multiple selections we should not clear this
          currentSelection = [selectionStart];
          redraw();
        }
  
       
  
      });

      //redraw();
      
//文档页面模板加载，关联点事事件，用于段落文本交互。
// const textCanvas = document.getElementById('textCanvas');
// textCanvas.addEventListener('click', onCanvasClick);

addPara(para_1,"Par0001","第一自然段");//增加一个自然段
addTable(my_jsonData,"Tab001","这是第一个表格");//将表格添加到templateDoc
addTable(my_jsonData2,"Tab002","这是第二个表格");
addPara(para_2,"Par0002","第二自然段");//增加一个自然段
addTable(my_jsonData2,"Tab003","这是第三个表格");
addTable(my_jsonData,"Tab004","这是第四个表格");
addPara(para_2,"Par003","第三自然段");//增加一个自然段
preloadImages(displayOnCanvas); // Preload any initial images and display
   
  });


  function setDefaultSelection(defaultValue) {
    const options = document.querySelectorAll('#lineSpacingOptionsLSS li');
    options.forEach(option => {
      if (option.getAttribute('data-value') === defaultValue) {
        option.classList.add('selected');
      } else {
        option.classList.remove('selected');
      }
    });
  }
  